Open In App

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

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In modern web applications, to change states with onClick event in React JS using functional components is done by Hooks in React as the functional components don’t have inbuilt states like class components. 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.

Prerequisites

Approach

Using useState hook to dynamically change the states with onClick event in react js. When clicking on the button the state for the component to be rendered is set to true and other to false.

Steps to create 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

Example: Switching components with onClick event to update state to true or false using useState hook.

Javascript




// Filename - App.js
 
import ComponentOne from "./components/ComponentOne";
import "./App.css";
 
function App() {
    return (
        <div className="App">
            <h1 className="geeks">GeeksforGeeks</h1>
            <h3>
                Change States with onClick Event in React JS
            </h3>
             
            <ComponentOne />
        </div>
    );
}
 
export default App;


Javascript




// Filename - components/ComponentOne.js
 
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>
            <div className="container">
                {description && (
                    <div>
                        <p>
                            This is a <b> descriptive </b>
                            component
                        </p>
                        <h3>Descriptions:</h3>
                    </div>
                )}
                {reviews && (
                    <div>
                        <p>
                            This is a <b> Review </b>
                            component
                            <br />
                        </p>
                        <h3>Reviews:</h3>
                    </div>
                )}
            </div>
        </div>
    );
}
 
export default ComponentOne;


CSS




/* Filename - App.js */
 
.App {
    text-align: center;
}
 
.geeks {
    color: green;
}
 
.container {
    width: 20rem;
    margin: auto;
    box-shadow: 0px 5px 10px gray;
    border-radius: 15px;
    padding: 3%;
}
 
button {
    font-size: large;
    margin: 2%;
    background-color: green;
    color: white;
    border-radius: 5px;
    padding: 10px;
}


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.

Peek-2023-10-18-11-26



Similar Reads

Differences between Functional Components and Class Components
In this article, we will learn about the differences between functional and class components in React with the help of an example. We will create a counter and implement it using both class and functional components to understand the differences practically. Functional Components Functional components are some of the more common components that wil
4 min read
Why it is Recommended to use Functional Components over Class Components ?
In this article, we will learn about the use of the functional component over the class component. In React JS, there are two main types of components:  Functional Components Class Components.Functional Components are JavaScript functions that take in props as an argument and return a React element to be rendered. They are simpler and less verbose
4 min read
Migrating from Class Components to Functional Components in React
React version 16.8.0 or higher allows users to write the functional components without the use of class components. Using class components, we need to write the whole class to interact with the state and lifecycle of the component. The code was quite complex and harder to understand which led to lower performance and limited usability. With the hel
4 min read
ReactJS Functional Components
Functional Component is one way to create components in a React Application. React.js Functional Components helps to create UI components in a Functional and more concise way. In this article, we will learn about functional components in React, different ways to call the functional component, and also learn how to create the functional components.
5 min read
How to change an element color based on value of the color picker value using onclick?
We can define color picker by input type="color". It provides a user interface element that lets a user specify a color, either by using a visual color picker interface or by entering the color into a text field in #rrggbb hexadecimal format. Only colors without alpha channels are allowed. Though CSS colors have more formats, e.g. color names, func
2 min read
How to stop event propagation with inline onclick attribute in JavaScript ?
Use HTML DOM stopPropagation() method to stop the event from propagating with inline onclick attribute which is described below: HTML DOM stopPropagation() Event Method: The stopPropagation() method is used to stop propagation of event calling i.e. the parent event is called we can stop the propagation of calling its children by using the stopPropa
2 min read
HTML DOM onclick Event
The HTML DOM onclick event occurs when the user clicks on an element. There are three ways to add onclick events: Syntax: In HTML: &lt;element onclick="myScript"&gt; In JavaScript: object.onclick = function(){myScript}; In JavaScript, using the addEventListener() Method: object.addEventListener("click", myScript); Example 1: Using HTML C/C++ Code
2 min read
jQuery click() Method vs onClick Event
jQuery is the JavaScript library known for its lightweight, fast, and cross-platform features. It is an open-source library that goes by the motto "Write less, do more". The main objective of jQuery is to make Java script so easy that one can create more attractive and interactive websites. jQuery has multiple events like jQuery onClick(), jQuery c
5 min read
Changing CSS styling with React onClick() Event
Changing CSS styling with React onClick() Event simply means changing the CSS property or CSS classes when the click event triggers. It can be done by switching the states to update the classes when a button is clicked PrerequisitesReact JSReact useState HookApproachChanging CSS styling with React onClick() Event we will use useState variable. We w
2 min read
Call multiple JavaScript functions in onclick event
To Call multiple JavaScript functions in onclick event, we have different approaches. In this article, we are going to see how to call multiple JavaScript functions in onClick event. Below are the approaches to calling multiple JavaScript functions in onclick event: Table of Content Calling all functions at onceCalling one function that contains re
2 min read
Article Tags :