'How to handle useState in React?
I'm a beginner in react.. I'm currently practicing by changing the code to FC.
In the process of manipulating the state in React, I put {value:"x"} using useState, but the value does not come out. Do you know where I am going wrong?
class code
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
};
}
render() {
return (
<button
className="square"
onClick={() => this.setState({value: "X"})}
>
{this.state.value}
</button>
);
}
}
FC code
function Square (props){
const [message , setMessage] = useState({value:null});
console.log(message);
return (
<button className="square" onClick={()=> setMessage({value:"x"}) } > //Error
{setMessage.value} //Error
</button>
)
}
Solution 1:[1]
You should use message.value instead of setMessage.value
function Square (props){
const [message , setMessage] = useState({value:null});
console.log(message);
return (
<button className="square" onClick={()=> setMessage({value:"x"})} >
{message.value}
</button>
)
}
In this useState, message is state to use, setMessage is for updating states
const [message , setMessage] = useState({value:null});
P/s: You have a syntax problem at onClick. I modified it for you too
Solution 2:[2]
You're confusing the two approaches, in the FC way, you should do setMessage("X") to store "X" as the value of message. To be consistent with your Class example, the FC should be like so:
function Square (props){
const [message , setMessage] = useState(null); // <--Here
console.log(message);
return (
<button className="square" onClick={() => setMessage("x")}>
{message}
</button>
)
}
But if what you want is to save an object as the value of message then it should be like this:
function Square (props){
const [message , setMessage] = useState({value:null});
console.log(message);
return (
<button className="square" onClick={() => setMessage({value:"x"})}>
{message.value}
</button>
)
}
Solution 3:[3]
setMessage() expects an object {value: "string"}, you are just passing a string ("x").
Also, to render the message in your component, you will have to access message.value.
function Square (props){
const [message , setMessage] = useState({value:null});
console.log(message);
return (
<button className="square" onClick={()=> setMessage({value: "x"}) } > //Error
{message.value} //Error
</button>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick Vu |
| Solution 2 | |
| Solution 3 | yinken |
