React Course: Diary App Example, Implementing the Home Page

React is a library widely used for building dynamic user interfaces. In this course, we will explore the basic concepts of React by creating a diary app. Along the way, we will also implement the Home page. The Home page will be the main screen where users can access the diary and write new entries. In this article, you will learn various techniques, including React’s component structure, state management, and routing.

1. Basic Concepts of React

React is a component-based library with user-defined components. Components are independent pieces of the UI, and each component can have state and props. In this course, we will cover key concepts of React, including JSX, components, props, state, and lifecycle.

1.1 JSX

JSX stands for JavaScript XML and allows you to include HTML-like syntax within your JavaScript code. Using JSX makes it intuitive to write UI components. JSX is converted to JavaScript objects during compilation.

const element = <h1>Hello, React!</h1>;

1.2 Components

The basic building blocks of React are components. Components can be divided into functional components and class components. We will mostly use functional components.

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

1.3 Props and State

Props are read-only data passed to components. On the other hand, state is mutable data managed within a component, directly affecting the UI when it changes.

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return <h1>Current Count: {this.state.count}</h1>;
  }
}

1.4 Lifecycle

React components have a lifecycle, and through this lifecycle, you can manage the creation, updating, and removal of components. Key lifecycle methods include componentDidMount, componentDidUpdate, and componentWillUnmount.

2. Designing the Diary App

Now, let’s start designing the diary app. The diary app should have features that allow users to write, edit, and delete diary entries. Additionally, users should be able to view their entries in a list format.

2.1 App Structure

The diary app can be divided into the following components:

  • Home: A screen that includes the diary list and a button to add a new entry
  • DiaryEntry: A component that displays each diary item
  • AddEntry: A component that includes a form to write a new diary

3. Implementing the Home Page

Now let’s implement the Home page. The Home page will include the diary list and a button to add a new diary entry. For this, we will create two components: the Home component and the DiaryEntry component.

3.1 Home Component

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

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

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

  return (
    <div>
      <h1>My Diary</h1>
      <AddEntry onAdd={addEntry} />
      <ul>
        {entries.map((entry, index) => (
          <DiaryEntry key={index} entry={entry} />
        ))}
      </ul>
    </div>
  );
}

export default Home;

3.2 DiaryEntry Component

import React from 'react';

function DiaryEntry({ entry }) {
  return (
    <li>
      <h2>{entry.title}</h2>
      <p>{entry.content}</p>
    </li>
  );
}

export default DiaryEntry;

3.3 AddEntry Component

import React, { useState } from 'react';

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

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

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={title} 
        onChange={(e) => setTitle(e.target.value)} 
        placeholder="Title" 
      />
      <textarea 
        value={content} 
        onChange={(e) => setContent(e.target.value)} 
        placeholder="Diary Content" 
      />
      <button type="submit">Add Diary</button>
    </form>
  );
}

export default AddEntry;

4. Complete App Code

Now, let’s assemble all the components to build the complete app. We will create an index.js file under the src directory.

import React from 'react';
import ReactDOM from 'react-dom/client';
import Home from './Home';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

5. Conclusion

In this React course, we learned the basic concepts of React and component-based design through the diary app. By implementing the Home page, we also gained an understanding of state management and how to pass props. Remember that React allows you to easily create user-friendly UIs!

Continue to explore advanced concepts of React by adding more features. Incorporating functionalities such as routing to other pages and saving/loading data will create a more complete app. Thank you!

React Course: Implementing the Edit Page in the Diary App Example

In this course, we will explain in depth how to create an Edit page while implementing a simple diary app using React. Through this process, you will understand the basic concepts of React and learn technologies such as state management, routing, and event handling.

1. Preparing the Project

First, you need to create a React project. You can easily get started using Create React App.

npx create-react-app diary-app

After moving to the project directory, install the necessary packages.

cd diary-app
npm install react-router-dom

2. Designing the Basic Structure

Define the basic structure of the diary app. Create pages to manage the diary and components to manage each diary entry.

2.1. Modifying the App.js File

Modify the App.js file to add routing.


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

function App() {
    return (
        
            
                
                
            
        
    );
}

export default App;

2.2. Home Component

The Home component is responsible for displaying the list of diaries. Here, we will create dummy data as an array for the example.


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

const Home = () => {
    const diaries = [
        { id: 1, title: 'First Diary', content: 'Today is a nice day.' },
        { id: 2, title: 'Second Diary', content: 'I am learning React.' },
    ];

    return (
        

Diary List

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

3. Creating the Edit Page

The Edit page will implement a form to modify the title and content of the selected diary.

3.1. Creating the Edit Component

Create an Edit.js file and implement it as follows.


import React, { useState } from 'react';
import { useParams, useHistory } from 'react-router-dom';

const Edit = () => {
    const { id } = useParams();
    const history = useHistory();
  
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        // Here you can send a PUT request to the server.
        console.log({ id, title, content });
        history.push('/');
    };

    return (
        

Edit Diary

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

3.2. State Management

In React, there are various methods to manage state. Here, we will use Simple State Management.

  • We will manage the title and content as state using React’s useState hook.
  • In the form submission handler, we log the data to send it to the server.

4. Server Integration

Now it’s time to integrate with actual data. You can use the Axios library to communicate with server APIs.

npm install axios

4.1. Implementing CRUD with Axios

Create a CRUD API that can showcase various CRUD operations. We will cover the basics of CRUD on GitHub and distributed servers.

5. Conclusion and Deployment

After writing all the code and testing the edit page, you can proceed to build for deployment. You can generate optimized deployment files by entering the command below.

npm run build

Conclusion

Through this course, we learned how to create a simple diary app using React and implement an Edit page. This process will be a good exercise for those who are new to React.

Adding more features and further developing it to communicate with an actual database will also be a good exercise!

React Course: Diary App Example – Implementing the Diary Page

React is a widely-used JavaScript library for modern web application development. In this tutorial, you will learn how to create a basic diary application using React. First, this article will define the functionalities of the diary app and the necessary tech stack, and then guide you through the process of implementing the Diary page step by step.

1. Diary App Functional Requirements

The basic functionalities of the diary app are as follows:

  • Ability to write and save diaries
  • Ability to view saved diaries in a list
  • Ability to select a specific diary and edit its content
  • Ability to delete a diary

We will look into the basic knowledge of React and other related technologies required to implement these functionalities.

2. Required Tech Stack

In this example, we will use the following tech stack:

  • React: A library for building user interfaces
  • React Router: A library for navigating between pages
  • Context API: React’s built-in API for state management
  • CSS: Basic styling using CSS

Now, let’s look at how to set up the React application in detail.

3. Setting Up the React Application

To create a new React application, use the npx create-react-app diary-app command. This command automatically generates the necessary files and folder structure needed to set up a basic React project.

npx create-react-app diary-app

After moving to the directory, let’s run the development server.

cd diary-app
npm start

Now you can open your web browser and check the basic React app at http://localhost:3000. Let’s start developing the diary application.

4. Creating the Diary Page Component

To create the Diary page component, create the src/components/Diary.js file. Then, set up the basic structure as shown below.

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

const Diary = () => {
    const { diaryEntries, addEntry, deleteEntry } = useContext(DiaryContext);
    const [entry, setEntry] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        addEntry(entry);
        setEntry("");
    };

    return (
        

Write a Diary

Saved Diary List

    {diaryEntries.map((e, index) => (
  • {e}
  • ))}
); }; export default Diary;

In the code above, we use the useContext hook to access diary data and the useState hook to manage input data. This sets up a form for writing entries and displays a list of saved diaries.

5. Setting Up DiaryContext

To manage diary data and share it with other components, we will set up DiaryContext. Create the src/components/DiaryContext.js file and add the following code.

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

export const DiaryContext = createContext();

export const DiaryProvider = ({ children }) => {
    const [diaryEntries, setDiaryEntries] = useState([]);

    const addEntry = (entry) => {
        setDiaryEntries([...diaryEntries, entry]);
    };

    const deleteEntry = (index) => {
        const newDiaryEntries = diaryEntries.filter((_, i) => i !== index);
        setDiaryEntries(newDiaryEntries);
    };

    return (
        
            {children}
        
    );
};

In this file, we defined the state that holds the list of diaries and the functions to update it. Now let’s configure this context to be used in the App.js file.

6. Modifying App.js

Open the App.js file and modify it as follows.

import React from 'react';
import { DiaryProvider } from './components/DiaryContext';
import Diary from './components/Diary';

const App = () => {
    return (
        
            

My Diary App

); }; export default App;

We have now wrapped the Diary component in the DiaryProvider to allow it to use diary data. Thus, we have completed the basic diary application.

7. Application Styling

Now let’s add some simple styles to the application. Add the following basic styles to the src/App.css file.

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

h1 {
    color: #333;
}

textarea {
    width: 100%;
    height: 100px;
    margin-bottom: 10px;
    padding: 10px;
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

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

Applying these styles provides a visually simple and comfortable user experience with a bright background.

8. Checking the Results

Now that we have completed all the settings and code, let’s actually check if the application works well by accessing http://localhost:3000 in a web browser.

Test the functionalities like writing a diary and deleting from the list.

9. Additional Feature Considerations

We have implemented the basic diary app so far. Additional features to consider include:

  • Edit Diary Feature: Add the ability for users to edit saved diaries.
  • Communication with the Server: Add the ability to retrieve or save diaries stored on a server.
  • Search and Filtering Features: Add functionality to search or filter the list of written diaries by date.
  • Style Improvements: Use CSS frameworks to provide better UX/UI.

10. Conclusion

In this lesson, we learned how to implement a simple diary app using React. It includes basic functionalities such as diary writing, displaying, and deleting. This fundamental app will help enhance your understanding of React and assist in adding more complex features as you develop further.

By utilizing various libraries and tools provided in the React ecosystem, you can enrich the user experience even more. We encourage you to create your own diary application. Thank you!

React Lecture: Storing Diary Data in Web Storage

Today’s web applications are grappling with how to efficiently manage and store user data. In this tutorial, we will explore how to store diary data in web storage using React. Web storage is a convenient and effective way to store data in the browser, allowing for more data to be stored than with Flash or cookies, and enabling easy reading and writing of data without the need for server requests.

1. What is Web Storage?

Web storage has two main types: Session Storage and Local Storage. While these two have different data storage methods, they provide the same API.

  • Local Storage: Allows for permanent data storage. The data does not disappear even if the user closes the browser or refreshes the page.
  • Session Storage: Data is only stored for the duration of the browser session. The data disappears when the user closes the tab or exits the browser.

Using local storage is the most suitable option for storing diary data, as the diary entries created by the user need to be preserved.

2. Creating a Diary App Using React and Web Storage

In this section, we will create a simple diary-writing application. The application will allow users to write diaries, save them in local storage, and retrieve the saved diaries. We will manage the state using React’s `useState` and `useEffect` hooks, and synchronize the data with web storage.

2.1 Project Setup

npx create-react-app diary-app

After creating the React app with the command above, navigate into the created directory.

cd diary-app

2.2 Creating Necessary Components

Here is the main component structure:

  • App.js
  • DiaryForm.js
  • DiaryList.js

2.3 DiaryForm Component

The DiaryForm component provides a form for users to input their diary entries.

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

const DiaryForm = ({ onSubmit }) => {
    const [diaryText, setDiaryText] = useState('');

    const handleSubmit = (e) => {
        e.preventDefault();
        onSubmit(diaryText);
        setDiaryText('');
    }

    return (
        
); }; export default DiaryForm;

2.4 DiaryList Component

The DiaryList component displays the saved diary entries.

import React from 'react';

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

Saved Diaries

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

2.5 App Component

The App component manages the overall state of the application and interacts with web storage.

import React, { useState, useEffect } from 'react';
import DiaryForm from './DiaryForm';
import DiaryList from './DiaryList';

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

    useEffect(() => {
        const savedDiaries = localStorage.getItem('diaries');
        if (savedDiaries) {
            setDiaries(JSON.parse(savedDiaries));
        }
    }, []);

    const addDiary = (diary) => {
        const updatedDiaries = [...diaries, diary];
        setDiaries(updatedDiaries);
        localStorage.setItem('diaries', JSON.stringify(updatedDiaries));
    };

    return (
        

Diary Application

); }; export default App;

3. Code Explanation

3.1 State Management

In the code above, we manage the state of diary data (`diaries`) using `useState`. When a user inputs a new diary entry, the `addDiary` function is called to update the state and saves it to local storage.

3.2 Using Web Storage

To save diaries in local storage, we use `localStorage.setItem` and `localStorage.getItem` methods. When the application first renders, we use `useEffect` to retrieve the saved diaries.

4. Running the Application

Once all the setup is complete, you can run the application with the command below.

npm start

You can check the diary application by accessing http://localhost:3000 in the browser.

5. Future Improvements

In addition to the basic features above, the following improvements can be considered:

  • Add diary editing and deletion features
  • Display the date and time of diary entries
  • Apply various UI styling
  • Implement functionality to search or filter diaries

6. Conclusion

In this tutorial, we built a simple application that saves and manages diary data using web storage with React. By using web storage, we can conveniently save user data, thereby enhancing the user experience of the application. Now you can create your own diary application!

7. Related Resources

React Course: Handling Events

React is a very useful library for building user interfaces. Event handling is essential for processing user input in React applications. In this course, we will delve deeply into how to handle events in React.

1. What are Events?

Events are specific actions or state changes that occur in the browser. For example, an event occurs when a user clicks a button or moves the mouse. React provides a way to easily handle these events, allowing you to change the application’s state through user interaction.

2. React’s Event System

React uses its own event system, which operates by using a virtual DOM instead of directly modifying the DOM to perform optimized updates. React events are similar to standard DOM events, but there are some differences.

2.1 SyntheticEvent

React creates a SyntheticEvent object for all events. This object wraps the browser’s native events to provide a standardized API. For example, SyntheticEvent provides the event.preventDefault() and event.stopPropagation() methods.

2.2 Registering Event Handlers

In React, event handlers can be registered through JSX attributes. For example, you can handle events using attributes like onClick, onChange, and onSubmit.


function MyButton() {
    function handleClick() {
        alert('The button has been clicked!');
    }

    return (
        <button onClick={handleClick}>Click here</button>
    );
}

3. Basics of Event Handling

The basic way to handle events in React is to define a function and pass that function to an event property in JSX, as described above. Here we will look at a few common event types.

3.1 Mouse Events

Mouse events play an important role in handling interactions with the user interface. Here are examples of mouse events:


function MouseEventExample() {
    function handleMouseOver() {
        console.log('The mouse is over the element!');
    }

    return (
        <div onMouseOver={handleMouseOver}>Mouse over test</div>
    );
}

3.2 Keyboard Events

Keyboard events occur when a user inputs through the keyboard. Here is a basic example of key input events:


function KeyEventExample() {
    function handleKeyPress(event) {
        console.log('Key pressed:', event.key);
    }

    return (
        <input type="text" onKeyPress={handleKeyPress} />
    );
}

3.3 Form Events

When using forms in React, it is important to utilize form events to manage input values. Here is an example of handling the form submit event:


function FormExample() {
    function handleSubmit(event) {
        event.preventDefault(); // Prevent default action
        console.log('Form has been submitted!');
    }

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" />
            <button type="submit">Submit</button>
        </form>
    );
}

4. Event Propagation and Binding

There are various ways to define event handlers in React, and they may function differently in class components and function components. This section will cover how to bind event handlers in class components.

4.1 Binding in Class Components

In class components, methods are not automatically bound to the instance of the class, so you need to bind the event handler methods. Here is an example using a class:


class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        alert('Clicked!');
    }

    render() {
        return (
            <button onClick={this.handleClick}>Click here</button>
        );
    }
}

4.2 Binding with Arrow Functions

In class components, using arrow functions to define methods automatically provides a binding effect:


class MyComponent extends React.Component {
    handleClick = () => {
        alert('Clicked!');
    }

    render() {
        return (
            <button onClick={this.handleClick}>Click here</button>
        );
    }
}

5. Event Propagation and Capturing

When an event occurs on a web page, event propagation occurs, which can be divided into two stages: capturing and bubbling. React supports both of these stages.

5.1 Capturing

Event capturing is the stage where the event starts at the top-level element and proceeds to the element where the event occurred. Event handlers can be processed during the capturing stage using properties like onClickCapture.


function CapturingExample() {
    function handleClickCapture() {
        console.log('Clicked during the capturing phase!');
    }

    return (
        <div onClickCapture={handleClickCapture}>
            <button> Please click </button>
        </div>
    );
}

5.2 Bubbling

Bubbling is the stage where the event propagates from the element where it occurred to the top-level element, and it is typically handled in standard event handlers like onClick. React’s event system can handle both of these.

6. Handling Multiple Events

In React applications, you often need to handle various events simultaneously. In this case, you can define multiple event handlers within a single component to manage each event:


function MultiEventExample() {
    function handleClick() {
        console.log('Button clicked');
    }

    function handleMouseOver() {
        console.log('Mouse over');
    }

    return (
        <button onClick={handleClick} onMouseOver={handleMouseOver}>Button</button>
    );
}

7. Event Handling with Custom Hooks

React allows you to create reusable logic using hooks. Implementing event handlers as custom hooks can improve the readability and maintainability of your code.


import { useState } from 'react';

function useEventHandler() {
    const [count, setCount] = useState(0);

    function increment() {
        setCount(count + 1);
    }

    return [count, increment];
}

function EventHandlerExample() {
    const [count, increment] = useEventHandler();

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={increment}>Increase</button>
        </div>
    );
}

8. Performance Optimization

Since event handling can occur frequently in React, performance optimization is important. Here are some ways to enhance performance:

8.1 Using React.memo

You can use React.memo to memoize components in React. This helps prevent unnecessary re-rendering.


const MyComponent = React.memo(function MyComponent({ onClick }) {
    return <button onClick={onClick}>Click here</button>;
});

8.2 Using useCallback Hook

By using the useCallback hook to memoize event handlers, you can avoid creating new handlers when the component re-renders.


import { useCallback } from 'react';

function EventOptimizationExample() {
    const handleClick = useCallback(() => {
        console.log('Clicked!');
    }, []);

    return <button onClick={handleClick}>Click here</button>;
}

9. Conclusion

In this course, we have taken a detailed look at handling events in React. By understanding React’s event system, various event types, and efficient event handling methods, you can implement better user interactions. We hope you will continue to utilize React to develop high-quality applications.

In the next course, we will cover state management and asynchronous processing in React. Let’s continue to explore the charm of React!