react setstate jsx functional component code example
Example 1: state with react functions
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
Example 2: react lifecycle example
class Test extends React.Component {
constructor() {
console.log('Constructor')
super();
this.state = {
count: 0
};
}
componentDidMount() {
console.log("component did mount");
}
componentDidUpdate() {
console.log("component did update");
}
onClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("render");
return (
<div>
Hello Test
<button onClick={this.onClick}>
{this.state.count}
</button>
</div>
);
}
}
//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update