React basic tutorial with example

 

React.js Basic Tutorial with Example

React is a popular JavaScript library for building user interfaces, particularly for single-page applications (SPAs) where you need a fast, interactive user experience. React allows you to build UI components that can update dynamically without needing to reload the whole page.

In this tutorial, we'll walk through the basic concepts of React and build a simple app from scratch. This example will include the following topics:

  1. Setting up a React project.
  2. Creating components.
  3. Using props and state.
  4. Handling events.
  5. Using hooks (specifically useState).

Step 1: Setting Up a React Project

To start working with React, the easiest way is to use Create React App, a tool that sets up everything for you.

  1. Open your terminal and run the following command to create a new React app:

    npx create-react-app react-basic-tutorial

    This will create a new folder called react-basic-tutorial with all the necessary files and dependencies for your React app.

  2. After the setup is complete, navigate into the new folder:

    cd react-basic-tutorial
  3. Now, start the development server:

    npm start

    This will run the app and open it in your default web browser at http://localhost:3000.


Step 2: Understanding the Folder Structure

The folder structure of a React app generated by Create React App looks like this:

java
react-basic-tutorial/ ├── node_modules/ ├── public/ │ └── index.html ├── src/ │ ├── App.js │ ├── index.js │ ├── App.css │ └── ... └── package.json
  • public/index.html: This is the main HTML file. React components are rendered into the div with the id="root".
  • src/index.js: This is the entry point for the React app. It renders the main App component.
  • src/App.js: This is the default app component, where we can define our main UI and logic.

Step 3: Creating a Simple Component

A component in React is a function (or a class) that returns a piece of UI (JSX) that will be rendered to the screen. We can create a simple component to display a message.

  1. Open src/App.js and modify it as follows:

    js
    // src/App.js import React from 'react'; function App() { return ( <div className="App"> <h1>Hello, welcome to React!</h1> </div> ); } export default App;
  2. Now, when you save the file, React will re-render the app and display the message on the page. This is the simplest form of a component that returns some static content.


Step 4: Using Props

Props (short for "properties") allow you to pass data from a parent component to a child component. Let’s create a component that takes in a name prop and displays a greeting message.

  1. First, create a new component called Greeting.js inside the src folder:

    js
    // src/Greeting.js import React from 'react'; function Greeting(props) { return <h2>Hello, {props.name}!</h2>; } export default Greeting;
    • This component receives props and renders a greeting message using the name prop.
  2. Now, go back to App.js and use the Greeting component, passing a name prop:

    js
    // src/App.js import React from 'react'; import Greeting from './Greeting'; function App() { return ( <div className="App"> <h1>Welcome to React!</h1> <Greeting name="John" /> <Greeting name="Sarah" /> </div> ); } export default App;
  3. When you save the file, the app will display two greeting messages:

    css
    Welcome to React! Hello, John! Hello, Sarah!

This demonstrates how you can reuse the Greeting component and pass different values for the name prop.


Step 5: Using State with useState Hook

State in React allows components to store data that can change over time. The useState hook is used to add state to functional components. Let's modify our app to include a counter with buttons to increase and decrease the count.

  1. In App.js, import the useState hook and create a state variable for the count:

    js
    // src/App.js import React, { useState } from 'react'; import Greeting from './Greeting'; function App() { // Declare a state variable 'count' with an initial value of 0 const [count, setCount] = useState(0); // Functions to handle increment and decrement const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); return ( <div className="App"> <h1>React State Example</h1> <Greeting name="John" /> <p>Current count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default App;
  2. In this code:

    • useState(0) creates a state variable count with an initial value of 0.
    • setCount is the function that will update the count value.
    • increment and decrement are functions that modify the count state when the buttons are clicked.
    • The onClick event handlers call these functions when the user clicks the buttons.
  3. When you save and run the app, you’ll see the following:

    • A Current count value.
    • Buttons to Increment and Decrement the count.

Step 6: Handling Events

React allows you to handle user interactions, like clicks, form submissions, and keyboard inputs, with event handlers. We've already seen the onClick event in action with the increment and decrement buttons.

Let's add an input field that updates the greeting message dynamically when the user types their name.

  1. Update App.js to include an input field that updates the name state:

    js
    // src/App.js import React, { useState } from 'react'; import Greeting from './Greeting'; function App() { const [count, setCount] = useState(0); const [name, setName] = useState(''); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const handleInputChange = (event) => { setName(event.target.value); // Update the name state as the user types }; return ( <div className="App"> <h1>React Event Handling Example</h1> <Greeting name={name || "Guest"} /> {/* Default to "Guest" if name is empty */} <input type="text" value={name} onChange={handleInputChange} placeholder="Enter your name" /> <p>Current count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); } export default App;
  2. Here:

    • We added a new state variable name with the useState hook to store the name entered by the user.
    • The handleInputChange function updates the name state as the user types in the input field.
    • We use the name state as a prop for the Greeting component to dynamically update the greeting message.
  3. When you run the app:

    • You will see a text input where you can type a name.
    • The greeting message will update in real-time as you type.
    • The count can still be incremented and decremented.

Conclusion

In this tutorial, you learned the following basic concepts of React:

  1. Components: Building blocks of a React app.
  2. Props: Passing data from parent to child components.
  3. State: Managing data within components using the useState hook.
  4. Event Handling: Responding to user interactions like button clicks and input changes.

By combining these concepts, you can start building more interactive and dynamic web applications with React. As you continue learning React, you can explore more advanced topics like component lifecycle, useEffect hook, context API, routing with React Router, and state management with Redux.

Comments

Popular posts from this blog

Top 200 telagu words in hindi daily life?

Building strong foundational knowledge in frontend development topics

Docker and Kubernetes Tutorials and QnA