I’m a beginner in react..
I’m currently practicing by changing the code to FP.
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 :
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