React Course: Diary App Example and Dynamic Route Routing with React Router

Hello! In this course, we will create a basic diary app using React. This app will allow users to write, edit, and delete diary entries. Additionally, we will use React Router to add dynamic path routing, so that each diary entry can be accessed individually. Through this article, I will help you gain a deep understanding of the basic concepts of React, state management, and routing.

1. What is React?

React is a UI library developed by Facebook that provides a component-based approach to building user interfaces. Using React, you can manage the state of the UI and automatically update it based on changes in data. Moreover, React allows you to create reusable components, enabling efficient organization of your application.

2. Project Setup

To create the diary app, we need to set up a React project. Use the command below to create a new React project.

npx create-react-app diary-app

This command will create a new React application named `diary-app`. Once the project is created, navigate to the project directory.

cd diary-app

3. Installing Required Libraries

To use React Router, you need to install the `react-router-dom` library. Please install it using the command below.

npm install react-router-dom

4. Project Structure

The basic folder structure of the diary app will be as follows:

  • src/
    • components/ – Stores React components.
    • pages/ – Defines individual pages.
    • App.js – The main application file.
    • index.js – The entry point.

5. Creating React Components

To build the basic UI structure of the diary app, we need to create several React components. For example, we will create and use the `Header`, `DiaryList`, `DiaryDetail`, and `DiaryForm` components.

5.1 Header Component

import React from 'react';

const Header = () => {
    return (
        

Diary

); }; export default Header;

5.2 DiaryList Component

This component is responsible for displaying the list of diary entries.

import React from 'react';
import { Link } from 'react-router-dom';

const DiaryList = ({ diaries }) => {
    return (
        

Diary List

    {diaries.map(diary => (
  • {diary.title}
  • ))}
); }; export default DiaryList;

5.3 DiaryDetail Component

This component shows the details of the selected diary entry.

import React from 'react';

const DiaryDetail = ({ diary }) => {
    return (
        

{diary.title}

{diary.content}

); }; export default DiaryDetail;

5.4 DiaryForm Component

This is the form for writing a new diary entry or editing an existing one.

import React, { useState } from 'react';

const DiaryForm = ({ onSubmit }) => {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        onSubmit({ title, content });
        setTitle('');
        setContent('');
    };

    return (
        
); }; export default DiaryForm;

6. Setting Up the Router

Now let’s set up the router in the `App.js` file. This file defines the routing logic for the entire application.

import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Header from './components/Header';
import DiaryList from './components/DiaryList';
import DiaryDetail from './components/DiaryDetail';
import DiaryForm from './components/DiaryForm';

const App = () => {
    const [diaries, setDiaries] = useState([]);

    const addDiary = (diary) => {
        setDiaries(prevDiaries => [...prevDiaries, { id: prevDiaries.length, ...diary }]);
    };

    return (
        
            
} /> } /> { const diary = diaries[match.params.id]; return diary ? :
No diary entry found.
; }} />
); }; export default App;

7. Dynamic Path Routing

Using React Router, we can implement dynamic path routing. In the example above, the path `/diary/:id` dynamically loads diary details based on the diary ID. At this time, `match.params.id` is used to retrieve the diary with that ID.

8. Running the Project

Once all of the above setup is complete, you can run the application using the command below.

npm start

Access the diary app by visiting http://localhost:3000 in your browser.

9. Conclusion

In this course, we created a simple diary app using React. This app includes basic CRUD functionality as well as dynamic path routing features using React Router. Through this process, you have gained an understanding of React components and routing that can be applied to real application development.

I hope this article has been helpful in your learning of React! In the next course, we will explore adding more features or other tools in the React ecosystem.

React Course: Diary App Example – Implementing Common Components 2: Editor Component

In this course, we will explore the process of implementing the Editor component as part of developing a diary app using React. The Editor component plays an important role by providing input fields necessary for users to write their diaries and helps manage the submitted content. In this article, I will explain in detail the design and implementation of the component, the necessary state management methods, and various features to enhance the user experience.

1. Overview of the Editor Component

The Editor component is a core component of the diary app, performing the following functions:

  • Providing a text area for user input
  • Functionality to save the title and content
  • Validating the input and providing error messages
  • An event handler to pass the submitted content to the parent component

Through these functions, users can write diaries and save them for later review.

2. Designing the Editor Component

Before designing the Editor component, we need to determine what data is required. The states managed in the component are as follows:

  • Title: State to capture the title of the diary
  • Content: State to capture the content of the diary
  • Error Message: State to store error messages resulting from input validation

Each state is managed using the useState hook.

2.1 State Initialization

import React, { useState } from 'react';

const Editor = ({ onSave }) => {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');
    const [error, setError] = useState(null);

    // ...
};

2.2 Defining Props

The Editor component will receive a save handler passed from the parent component via a prop called onSave. This handler is called when the user writes and saves their diary.

3. Handling Input

The input elements used in the Editor include two input elements for the title and content, and one textarea element. Event handlers are set up to update the state when input occurs.

3.1 Input Event Handlers

const handleTitleChange = (event) => {
    setTitle(event.target.value);
};

const handleContentChange = (event) => {
    setContent(event.target.value);
};

3.2 Render Method

Now we will define how the Editor component will render based on the state and event handlers. The JSX structure containing the input fields and save button is as follows:

return (
    

Write a Diary

{error &&

{error}

}
);

4. Implementing the Save Functionality

To save the diary written by the user, we implement the handleSave function, which is called when the save button is clicked. This function includes logic to validate the input values and call the parent’s onSave handler if there are no issues.

4.1 Validating Input

const handleSave = () => {
    if (!title || !content) {
        setError('Title and content are required fields.');
        return;
    }
    setError(null);
    onSave({ title, content });
    // Clear input fields
    setTitle('');
    setContent('');
};

5. Integration: Using the Editor Component in Parent

The Editor component with the save functionality implemented needs to be integrated with other parts of the user interface. The parent component will use the Editor to save the written diary and add it to the list.

import React, { useState } from 'react';
import Editor from './Editor';

const DiaryApp = () => {
    const [entries, setEntries] = useState([]);

    const handleSaveEntry = (entry) => {
        setEntries([...entries, entry]);
    };

    return (
        

My Diary

    {entries.map((entry, index) => (
  • {entry.title}

    {entry.content}

  • ))}
); }; export default DiaryApp;

6. Conclusion and Additional Features

In this article, we covered the process of implementing the Editor component for a diary app using React. Basic functionality for users to write and save diaries has been established. Additionally, the following features can be considered:

  • Functionality to edit saved diaries
  • Diary deletion functionality
  • Functionality to sort or filter diaries by date
  • Functionality to save written diaries to local storage or a server

The experience of combining various components and managing state to create an interactive app using React is very rewarding. I encourage you to continue studying and challenging yourself on various topics!

React Course: Implementing Button and Header Components for a Diary App

This course provides a step-by-step explanation of how to implement common components like
Button and Header for a diary application using React.
The diary app is a web application that allows users to write and save their diaries,
and it is recommended to use React to make the basic UI components familiar.

What is React?

React is a JavaScript library for building user interfaces.
When building the UI of web applications, it maximizes reusability and efficiency through a component-based structure.
React allows for easy management and updating of dynamic UIs using state and props.

What are Common Components?

Common components refer to UI elements that can be reused in multiple places.
In the diary application, elements such as Button and Header are frequently used,
so separating them into components can reduce code duplication and make maintenance easier.

Project Setup

Before starting the project, you need to set up the React environment.
To start a new React application, enter the following command to create a React app:

npx create-react-app diary-app

Then, navigate to the created directory and run the project:

cd diary-app
npm start

Implementing Common Components

1. Button Component

Button component is responsible for creating a clickable button.
This component allows for the easy addition of various button styles and functionalities.
Let’s create the Button component with the code below.


import React from 'react';
import './Button.css'; // CSS file for styling

const Button = ({ onClick, children, className }) => {
    return (
        
    );
};

export default Button;
    

In the above code, the Button component receives three properties:

  • onClick: The function to be called when the button is clicked
  • children: The content to be placed inside the button
  • className: A property that allows the application of additional CSS classes

Now, let’s create a Button.css file to define the styles.
We will set the basic style of the button as follows.


.button {
    padding: 10px 20px;
    font-size: 16px;
    color: white;
    background-color: #007bff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.button:hover {
    background-color: #0056b3;
}
    

2. Header Component

Header component contains the title and other elements displayed at the top of the application.
Let’s implement the Header component with the code below.


import React from 'react';
import './Header.css';

const Header = () => {
    return (
        

My Diary

); }; export default Header;

The above code creates a simple Header component that includes the title of the diary.
Create a Header.css file and specify the styles as follows.


.header {
    padding: 20px;
    background-color: #f8f9fa;
    text-align: center;
    border-bottom: 1px solid #dee2e6;
}
.header h1 {
    margin: 0;
    color: #333;
}
    

Integrating into the App Component

Now, let’s use the implemented Button and Header components in App.js.
Modify App.js as below to integrate the two components.


import React from 'react';
import Header from './Header';
import Button from './Button';

const App = () => {
    const handleButtonClick = () => {
        alert('Button has been clicked!');
    };

    return (
        

Write a Diary

); }; export default App;

Conclusion

In this course, we explored how to implement common components of the diary application,
Button and Header, using React.
By creating these common components, we can enhance code reusability and simplify maintenance.
If you have gained a deeper understanding of the basics of React components, it will greatly help you in developing more complex applications in the future.

Additional Learning Resources

The official React documentation offers more information and examples about components.
If you want to deepen your understanding of React, please refer to the links below.

React Course: Diary App Example

Setting Common Styles

Hello! In this React tutorial, we will learn about React and how to set common styles through a diary app example. React is a component-based library that is very useful for building user interfaces. The diary app we will develop in this tutorial will be an application where users can record their thoughts and feelings.

Project Setup

First, we will create a new React project. For this, we will use create-react-app. Run the command below to set up the project:

    npx create-react-app diary-app
    cd diary-app
    npm start
    

Setting Common Styles

To ensure visual consistency in the diary app, we need to set common styles. Generally, styles can be set through a CSS file, but in React, we can use methods such as styled-components or CSS Modules. Here, we will simply use the App.css file to set up styles.

Creating Basic Styles

First, open the src/App.css file and add the basic styles as follows:

    body {
        background-color: #f0f4f8;
        font-family: 'Arial', sans-serif;
        margin: 0;
        padding: 0;
    }

    h1 {
        color: #333;
        text-align: center;
    }

    .diary-entry {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 15px;
        margin: 10px 0;
        background: #fff;
        box-shadow: 1px 1px 5px rgba(0,0,0,0.1);
    }

    .entry-title {
        font-size: 1.5em;
        color: #007acc;
    }

    .entry-date {
        color: #888;
        font-size: 0.9em;
    }

    .entry-content {
        margin-top: 10px;
        font-size: 1.1em;
    }
    

Creating a Diary Component

We will create a new component to display diary entries. Create a file named src/DiaryEntry.js and write as follows:

// src/DiaryEntry.js
import React from 'react';
import './App.css';

const DiaryEntry = ({ title, date, content }) => {
    return (
        

{title}

{date}

{content}

); }; export default DiaryEntry;

Final Structure of the Diary App

Now, let’s open the src/App.js file and write as follows:

// src/App.js
import React from 'react';
import DiaryEntry from './DiaryEntry';
import './App.css';

const App = () => {
    const diaryEntries = [
        { title: 'First Diary', date: '2023-10-01', content: 'Today was really a happy day!' },
        { title: 'Second Diary', date: '2023-10-02', content: 'It\'s a rainy day. I feel a little down.' },
        { title: 'Third Diary', date: '2023-10-03', content: 'I looked at the sky while reading a good book.' },
    ];

    return (
        

My Diary

{diaryEntries.map((entry, index) => ( ))}
); }; export default App;

State Management and Styling

To enhance the styles of the diary app, various styles can be applied along with state management. For example, implementing features to add and delete diary entries can improve user experience.

Using State Management Libraries

We will use the useState and useEffect hooks for state management in React. Add the code below to src/App.js to implement the feature for adding diary entries:

import React, { useState } from 'react';
// import DiaryEntry from './DiaryEntry';
// import './App.css';

const App = () => {
    const [entries, setEntries] = useState([
        { title: 'First Diary', date: '2023-10-01', content: 'Today was really a happy day!' },
        { title: 'Second Diary', date: '2023-10-02', content: 'It\'s a rainy day. I feel a little down.' },
    ]);

    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');

    const addEntry = () => {
        const newEntry = {
            title,
            date: new Date().toLocaleDateString(),
            content,
        };
        setEntries([...entries, newEntry]);
        setTitle('');
        setContent('');
    };

    return (
        

My Diary

setTitle(e.target.value)} />
); }; export default App;

Conclusion

Now we have learned how to set up a diary app using React and how to set common styles. Through these basic elements, we have established a foundation necessary to develop more complex applications. Upcoming topics will include styling libraries, data fetching, and more complex state management patterns. I hope you continue to learn and practice React to become a better developer!

React Course: Diary App Example – Implementing the New Page

Author: [Author Name] | Date: [Date]

Introduction

React is a JavaScript library for building user interfaces. In this tutorial, we will cover the process of creating a diary app using React. We will implement the app’s “New” page, where users can create and save a new diary entry. This tutorial will provide detailed explanations of the basic concepts of React, including component design, state management, and event handling.

Prerequisites

To follow this tutorial, you will need the following prior knowledge:

  • Basic understanding of HTML and CSS
  • Basic syntax of JavaScript
  • Basic concepts of React (components, props, state, etc.)

Additionally, you must have Node.js and npm installed, and know how to start a project using create-react-app.

Setting Up the Project

First, create a new React project. Open your terminal and enter the following command to create a project using create-react-app:

npx create-react-app diary-app

Once the project is created, navigate to the folder and run the development server:

cd diary-app
npm start

Your basic React app should now be running. Next, we will install the necessary dependencies. Since we will be using React Router, enter the following command to install it:

npm install react-router-dom

Setting Up the Router

To set up the router, open the src/App.js file and add the following code:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import NewEntry from './components/NewEntry';

function App() {
    return (
        
            
                
                
            
        
    );
}

export default App;

In the code above, we defined two routes. The Home component is rendered at the ‘/’ path, and the NewEntry component is rendered at the ‘/new’ path.

Creating the NewEntry Component

Now, to implement the page for writing a new diary entry, create the src/components/NewEntry.js file and write the following code:

import React, { useState } from 'react';

function NewEntry() {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        // Add diary saving logic here
        console.log('Title:', title);
        console.log('Content:', content);
    };

    return (
        

Create New Diary Entry

setTitle(e.target.value)} />
); } export default NewEntry;

The code above manages the title and content as state, and logs to the console when the form is submitted. Now it’s time to add the diary saving logic.

Adding Diary Saving Logic

The diary saving logic can be implemented in various ways. Let’s take a look at a simple method to save it in local storage. Add the following code in the handleSubmit function of the NewEntry component:

const handleSubmit = (e) => {
    e.preventDefault();

    const newEntry = { title, content, date: new Date() };
    let entries = JSON.parse(localStorage.getItem('entries')) || [];
    entries.push(newEntry);
    localStorage.setItem('entries', JSON.stringify(entries));

    // Reset
    setTitle('');
    setContent('');
};

With this, when the user writes a diary entry and clicks the save button, the new diary entry will be stored in local storage. We have reset the state to allow the user to easily write the next diary entry.

Checking the Results

Now let’s write a new diary entry and check the saved content. We can update the Home component to display the list of saved diary entries. Open the src/components/Home.js file and write the following code:

import React, { useEffect, useState } from 'react';

function Home() {
    const [entries, setEntries] = useState([]);

    useEffect(() => {
        const storedEntries = JSON.parse(localStorage.getItem('entries')) || [];
        setEntries(storedEntries);
    }, []);

    return (
        

Diary Entries

    {entries.map((entry, index) => (
  • {entry.title}

    {entry.content}

    {entry.date}
  • ))}
); } export default Home;

Now, the list of diary entries created by the user will be displayed on the home page. You will be able to see the diary titles, content, and the date as well.

Adding Styling

To make the React app more polished, let’s add some CSS styles. Open the src/App.css file and add the following styles:

body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 20px;
}

h1, h2, h3 {
    color: #333;
}

form {
    background: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

input, textarea {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    padding: 10px 15px;
    background: #28a745;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background: #218838;
}

Now the overall design of the app has improved, providing a user-friendly experience.

Conclusion

In this tutorial, we explored in detail how to implement the “New” page of a diary app using React. We provided basic functionalities for users to write and save new diary entries, allowing them to learn about component structure and state management concepts in React. Additionally, we also learned how to save data using local storage and style using CSS.

We hope you think about adding more advanced features and expanding the app in the future. Use React’s capabilities to create your own amazing projects!

Author: [Author Name] | [Contact Information]