How to change state value of a component from another component in react | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to change state value of a component from another component in react

In Nav.js const [ score, setScore] = useState(0); From App.js this should the score should increment by 1. But how

19th Jan 2021, 5:27 PM
Aman Kumar
Aman Kumar - avatar
4 Answers
+ 2
Pass setScore as prop to another component and change the score in there by setting setScore(1). If you can show your code it will be easier to help.
19th Jan 2021, 5:45 PM
Abhay
Abhay - avatar
0
App.js import logo from './logo.svg'; import './App.css'; import Nav from "./Component/nav.js"; function App() { return ( <div className = "App"> <div className = "nav"> <Nav /> </div> <button onClick={setScore(score + 1)}>Increment</button> </div> ); } export default App; ////////////////////////////// Nav.js import {useState} from 'react' import './Style Components/nav.css'; function Nav(){ const [score, setScore] = useState(0); return ( <div className = "nav-container"> <div className="score" id="score"> {score} {console.log(score)} </div> </div> ); } export default Nav;
20th Jan 2021, 3:36 AM
Aman Kumar
Aman Kumar - avatar
0
Aman Kumar so what you are looking for is a way to pass a prop from child component to parent component if I am not wrong, and sorry I can't help you with that ,you can however ask a new question with a title "how to pass prop from child to parent component in react" with your code snippet .
20th Jan 2021, 10:14 AM
Abhay
Abhay - avatar
0
Ok
20th Jan 2021, 4:38 PM
Aman Kumar
Aman Kumar - avatar