updating state in react code example
Example 1: Updating an object with setState in React
this.setState(prevState => {
let jasper = Object.assign({}, prevState.jasper);
jasper.name = 'someothername';
return { jasper };
})
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
Example 2: set state
class App extends React.Component {
state = { count: 0 }
handleIncrement = () => {
this.setState({ count: this.state.count + 1 })
}
handleDecrement = () => {
this.setState({ count: this.state.count - 1 })
}
render() {
return (
<div>
<div>
{this.state.count}
</div>
<button onClick={this.handleIncrement}>Increment by 1</button>
<button onClick={this.handleDecrement}>Decrement by 1</button>
</div>
)
}
}
Example 3: 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 4: update state in react
You have to use setState() for updating state in React
{
hasBeenClicked: false,
currentTheme: 'blue',
}
setState({
hasBeenClicked: true
});
Example 5: set state
setState({ searchTerm: event.target.value })
Example 6: reactjs update state example
{
hasBeenClicked: false,
currentTheme: 'blue',
}