Friday, December 27, 2024
Google search engine
HomeLanguagesHow to change states with onClick event in ReactJS using functional components...

How to change states with onClick event in ReactJS using functional components ?

In modern applications, writing functional components has become the ​standard way of writing React components as they are simply JavaScript functions that accept props and return a React element.

One can use Hooks only in the Functional component and this is a much easier way of managing the state as compared to the class component. With Hooks, state objects are completely independent of each other, so you can have as many state objects as you want. In a single-page application, the useState hook is the best way to simply change the state with a click without reloading the entire page.

React useState hook: The useState hook takes the initial state as an argument and returns a variable with the current state value (not necessarily the initial state) and another function to update this value.

Example: Program to demonstrate the state change on click. In this example, we have two buttons descriptions and reviews and we want to change the content when the button is clicked.

Creating React Application:

Step 1: Create a React application using the following command.

npx create-react-app projectname

Step 2: After creating your project folder i.e. projectname, move to it using the following command.

cd projectname

Project Structure: It will look like this.

 

Step 3: To use useState you need to import useState from react as shown below:

import { useState } from "react";
const [description, setDescription] = useState(true);
const [reviews, setReviews] = useState(false);

Set click event handler function of the element upon which click, results in changing state. In the ComponentOne.js file write the following code.

Javascript




import { useState } from "react";
function ComponentOne() {
    const [description, setDescription] = useState(true);
    const [reviews, setReviews] = useState(false);
    const descriptionHandler = () => {
        setDescription(true);
        setReviews(false);
    };
    const reviewsHandler = () => {
        setDescription(false);
        setReviews(true);
    };
    return (
        <div>
            <button onClick={descriptionHandler}>
                Descriptions</button>
            <button onClick={reviewsHandler}>
                Reviews</button>
            {description && (
                <p>
                    This is a <b>descriptive</b> button
                    <h3>Descriptions:</h3>
                </p>
            )}
            {reviews && (
                <p>
                    This is a <b>Review</b> button
                    <h3>Reviews:</h3>
                </p>
            )}
        </div>
    );
}
 
export default ComponentOne;


Step 4: In this code, when we click a  button the React onClick event handler enables you to call a function and trigger an action, in our case suppose when the review button is clicked it calls a function reviewsHandler, and inside this function the content/state changes by using the useState hook.

Javascript




import ComponentOne from "./components/ComponentOne";
 
function App() {
    return (
        <div>
            <ComponentOne />
        </div>
    );
}
 
export default App;


Step 5: Write the following code in index.js file. 
 

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
 
ReactDOM.render(<App />,document.getElementById('root'));


Step to run the application: Run the application using the following command:

npm start

Output: Now, open the URL http://localhost:3000/, and you will see the following output.

 

Conclusion: Instead of a class Component, the functional component is a simple and extensible way of changing the state on click in ReactJS without reloading the entire page with the useState hook.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments