Archive until 15 Jul 2021/Learning React
React - switching from class way to functional way (ft. hooks)
hajinny
2021. 1. 2. 17:59
Imagine we have the following code:
class SomeComponent extends React.Component{
constructor(props){
super(props);
this.state = {
custom: 'some stuff',
};
}
const onAction(){
this.setState({custom:'that stuff changed'});
}
render(){
return (
<div>
<div>Some Label with a custom state {this.state.custom}</div>
<button onAction={this.onAction}>Click me!</button>
</div>
);}
}
We can write the same code in a functional way!
const SomeComponent = ()=>{
const [custom, setCustom] = React.useState('some stuff');
const onAction = (e)=>{
setCustom('that stuff changed');
}
return (
<div>
<div>this is displaying some stuff {custom}</div>
<button onAction={onAction}>
</div>
);
}