Հայերեն Русский

Lesson 16: Introduction to React JS: Understanding Components and JSX


Introduction to React JS

What is React?

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It was developed by Facebook and is maintained by Facebook and a community of individual developers and companies. React has become one of the most popular and widely used libraries in modern web development due to its innovative approaches to rendering and updating user interfaces.

Key Features of React:

  1. Virtual DOM:

    • React creates a lightweight in-memory version of the actual DOM, known as the Virtual DOM. When changes in the UI occur, React first applies those changes to the Virtual DOM instead of the real DOM. It then calculates the most efficient way to update the real DOM to match the Virtual DOM. This process minimizes direct manipulations of the DOM, which are costly in terms of performance.
  2. One-Way Data Binding:

    • React follows a unidirectional data flow, meaning data has one, and only one, way to be transferred to other parts of the application. This approach makes the flow of data predictable and easier to understand, which simplifies debugging and enhances maintainability.
  3. Component-Based Architecture:

    • React is built around the concept of components. A component is a self-contained module that manages its own state and renders itself based on the data passed to it. Components can be reused throughout the application, which can lead to a more efficient development process as reusable components reduce the amount of code developers need to write.

Why Use React?

Efficiency:

Reusability of Components:

Extensive Ecosystem:

Strong Community and Backing:

Setting Up the Development Environment

To start working with React, one of the quickest and easiest methods is to use Create React App, a comfortable environment setup for React applications.

Steps to Set Up a React Project with Create React App:

  1. Install Node.js:

    • Node.js is required to run JavaScript on the server. Ensure it is installed on your machine.
  2. Install Create React App:

    • Open your terminal and install Create React App globally using npm:
      npm install -g create-react-app
      
  3. Create a New React Application:

    • Once the installation is complete, you can create a new React project:
      create-react-app my-react-app
      
    • This command creates a new folder named my-react-app with all the necessary setup, including a development server, webpack configuration, and Babel presets.
  4. Start the Development Server:

    • Navigate into your new project folder and start the development server:
      cd my-react-app
      npm start
      
    • This will run the development server and open your new React application in a web browser.

This setup gives you a solid foundation for developing React applications, with a build system and local server ready to go out of the box.

By the end of this introductory segment, students should have a clear understanding of what React is, why it's beneficial, and how to set up their development environment to start building React applications.

Understanding Components and JSX in React

Components as Building Blocks

In React, components are the fundamental building blocks of the user interface. A component in React encapsulates everything it needs to function on its own—markup, styles, and behavior—making them self-sufficient and reusable. Components manage their own state (data) and are responsible for rendering themselves based on this state and the props (properties) they receive from their parent components.

Characteristics of React Components:

Introduction to JSX

JSX (JavaScript XML) is a syntax extension for JavaScript commonly used with React to describe what the UI should look like. JSX combines HTML with JavaScript functionality, allowing developers to write HTML structures in the same file as JavaScript code.

Features of JSX:

Example of JSX:

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

JSX vs. HTML:

Writing Your First Component

Let's create a simple React component called Greeting that displays a greeting message. This component will illustrate the basic structure of a React component using JSX.

Example of a Simple Component:

import React from 'react';

function Greeting() {
    return <h1>Hello, React!</h1>;
}

In this example, Greeting is a functional component, which is one of the types of components you can define in React. It returns JSX that describes the UI.

Rendering Components

Components need to be rendered into the DOM to be visible. This is typically done using ReactDOM.render(), which handles updating the DOM to match the React elements.

Rendering a Component:

import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';

ReactDOM.render(<Greeting />, document.getElementById('root'));

This approach keeps React's rendering performance optimized, as React only changes individual DOM nodes as necessary rather than refreshing the entire UI on each update.

Hands-on Exercise:

  1. Create a New Component: Ask students to create a new component called UserProfile that displays a user's name and email.
  2. Render the Component: Guide them to render this component in the root DOM element of their application.

By guiding students through creating and rendering their first React component, they will gain hands-on experience with React's component-based architecture and JSX syntax. This foundational knowledge is crucial for building more complex components and applications using React.

Props and State in Functional Components

Props for Configuration

Props, short for properties, are a way of passing data from parent to child components in React. They are read-only, which means the data a component receives from its props should not be changed by the component itself. Props can include anything from strings and numbers to more complex data structures and functions.

Features of Props:

Example of Defining and Using Props:

// A child component that accepts props
function UserProfile({ username, email }) {
    return (
        <div>
            <h1>{username}</h1>
            <p>{email}</p>
        </div>
    );
}

// A parent component that passes props to the child
function App() {
    return <UserProfile username="JaneDoe" email="jane@example.com" />;
}

In this example, UserProfile is a functional component that takes props as an argument and uses them to display data. The parent component App passes username and email as props to UserProfile.

State Management Basics

While props allow you to pass data down to your components, state allows components to manage and respond to data that changes over time. Unlike props, state is local to the component and can be changed.

Using the useState Hook: React hooks, introduced in React 16.8, allow you to use state and other React features in functional components. The useState hook lets you add React state to functional components.

import React, { useState } from 'react';

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

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

Hands-On Exercise: Personalized Greeting Component

Objective: Enhance the greeting component to accept user input and display a personalized greeting. Use props for configuration and state to manage user interactions.

Setup:

  1. Create a Greeting Component with Props and State:

    import React, { useState } from 'react';
    
    function Greeting({ initialName }) {
        const [name, setName] = useState(initialName);
    
        return (
            <div>
                <h1>Hello, {name}!</h1>
                <input
                    type="text"
                    value={name}
                    onChange={e => setName(e.target.value)}
                />
            </div>
        );
    }
    
  2. Render the Greeting Component in the App:

    function App() {
        return <Greeting initialName="React Developer" />;
    }
    

In this exercise:

This exercise will solidify the students' understanding of how to effectively use props for passing data and configurations, and how state can be managed within functional components using hooks. This fundamental knowledge is crucial for building interactive and dynamic applications in React.

Practical Exercises and Component Composition in React

Building a Small Application: Simple Task List

This practical exercise involves creating a small React application—a task list where each task is a component. This application will demonstrate how to use props, state, and component composition effectively.

Objective: Students will build a simple task list application using React. Each task will have its description and a button to mark the task as completed, showcasing how components manage their state and interact with each other.

Steps to Build the Task List Application:

  1. Setup the Project:

    • Ensure that all students have their development environment set up with Create React App. This tool provides a good starting point with a built-in development server, Webpack, and Babel configurations.
    npx create-react-app task-list-app
    cd task-list-app
    npm start
    
  2. Create Task Component:

    • Define a Task component that accepts a task description and an event handler as props. This component will display the task and a button to mark it as done.
    function Task({ description, onComplete }) {
        return (
            <div className="task">
                <p>{description}</p>
                <button onClick={onComplete}>Mark as Done</button>
            </div>
        );
    }
    
  3. Create TaskList Component:

    • The TaskList component will manage the state of the tasks, including adding new tasks and marking tasks as completed.
    import React, { useState } from 'react';
    import Task from './Task';
    
    function TaskList() {
        const [tasks, setTasks] = useState([
            { id: 1, text: 'Learn React', completed: false },
            { id: 2, text: 'Write a new Component', completed: false }
        ]);
    
        const completeTask = taskId => {
            const newTasks = tasks.map(task => {
                if (task.id === taskId) {
                    return { ...task, completed: true };
                }
                return task;
            });
            setTasks(newTasks);
        };
    
        return (
            <div>
                {tasks.map(task => (
                    <Task
                        key={task.id}
                        description={task.text}
                        onComplete={() => completeTask(task.id)}
                    />
                ))}
            </div>
        );
    }
    
  4. Integrate TaskList in the App Component:

    • Replace the content of App.js with the TaskList component.
    import React from 'react';
    import TaskList from './TaskList';
    
    function App() {
        return (
            <div className="App">
                <h1>Task List</h1>
                <TaskList />
            </div>
        );
    }
    
    export default App;
    

Component Composition

Component composition is a powerful concept in React that allows developers to build complex UIs by nesting and combining components, similar to how HTML elements are nested.

Best Practices for Component Composition:

Conclusion

This exercise not only helps students understand and implement component composition but also gives them hands-on experience in managing the state and props in a real-world application scenario. They learn how to structure an application into manageable, reusable components that interact to create dynamic and interactive user interfaces. Through this exercise, students gain the confidence to tackle larger and more complex React projects.

Wrap-up and Q&A

As we conclude our comprehensive introduction to React, let's briefly recap the essential concepts we've explored today. This review will solidify your understanding and help ensure you're well-prepared to apply these concepts in your projects.

Review and Summary

1. Components as Building Blocks:

2. Introduction to JSX:

3. Props for Configuration:

4. State Management Basics:

5. Practical Exercises and Component Composition:

Q&A Session

Now, let's open the floor for any questions you may have. This is an excellent opportunity to clarify any part of the lesson that you found challenging or to discuss how you might apply these concepts in your own projects. Here are a few prompts to consider:

Feel free to ask questions or share insights based on your experiences. This discussion can provide valuable insights and help deepen everyone's understanding of React and its ecosystem. Whether you're planning a new project or refactoring an old one, the concepts we've covered today are crucial tools in your web development arsenal.