Here’s an example of a React class component that changes the state object:
import React from 'react';
class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
message: 'Hello, World!'
};
}
handleClick = () => {
this.setState({
counter: this.state.counter + 1,
message: 'Button Clicked!'
});
};
render() {
const { counter, message } = this.state;
return (
<div>
<h1>{message}</h1>
<p>Counter: {counter}</p>
<button onClick={this.handleClick}>Click me</button>
</div>
);
}
}
export default MyClassComponent;
In this example, the class component MyClassComponent
has a constructor where we initialize the state
object with two properties: counter
and message
. Inside the render
method, we destructure the state properties and use them to display the message and counter value. There’s also a button with an onClick
event that calls the handleClick
method when clicked.
The handleClick
method uses setState
to update the state object. It sets the counter
property to the current counter value plus one and changes the message
property to ‘Button Clicked!’. React will then re-render the component with the updated state.
Remember to import React and export the component at the end to use it in other parts of your application.