What is the use of setElement function in ReactJS ?
Last Updated :
28 Nov, 2023
In ReactJS we have a useState Hook this hook is used to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable.
Prerequisites:
Syntax:
const [ element , setElement ] = useState(initial_state);
Approach:
- Import React and useState:
- Import React and the `useState` hook to enable state management in the functional component.
- Define State and Click Handler:
- Use `useState` to create a state variable `element` initialized to 0.
- Implement a click handler function `onClickButtonHandler` that updates the state by incrementing `element`.
- Render JSX:
- Return JSX to render the component, displaying "GeeksforGeeks," the current value of `element`, and a button that triggers the click handler to increment `element` on each click.
Steps to Create the React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project structure: It will look like the following.
Project structureThe updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Change the state of the element using the setElement function.
JavaScript
import React, { useState } from 'react'
import './App.css'
function App() {
const [element, setElement] = useState(0);
function onClickButtonHandler() {
setElement(element + 1);
}
return (
<div className='App'>
<h1>GeeksforGeeks</h1>
<p>Add = {element}</p>
<button onClick={onClickButtonHandler}>
ADD
</button>
</div>
)
}
export default App;
CSS
/* Write CSS Here */
.App {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
body {
background-color: antiquewhite;
}
p {
font-size: 25px;
color: rgb(0, 167, 228);
font-weight: bold;
}
button {
width: 10em;
height: 2em;
background-color: rgb(27, 24, 24);
font-weight: 600;
font-family: 'Lucida Sans', 'Lucida Sans Regular',
'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
color: white;
border-radius: 6px;
border: none;
}
button:hover {
background-color: rgb(96, 145, 125);
}
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Output