Listing 6-1: Changing local variables doesn't update the view
My number is: 0
props.theNumber is: 0
import {useState} from 'react';
function App(){
const [theNumber,setTheNumber] = useState(0);
return (
<PropsMutator theNumber = {theNumber} setTheNumber = {setTheNumber} />
)
}
function PropsMutator(props){
let myNumber = props.theNumber;
const changeProp = ()=>{
myNumber = myNumber + 1;
console.log("my number is: " + myNumber);
}
return (
<>
<h1>My number is: {myNumber}</h1>
<h1>props.theNumber is: {props.theNumber}</h1>
<button onClick = {changeProp}>change myNumber</button><br />
<button onClick={()=>{props.setTheNumber(props.theNumber + 1)}}>
use setTheNumber
</button>
</>
)
}
export default App;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.