...

/

Managing the Component State in React

Managing the Component State in React

Learn how to manage component state in React using TypeScript, allowing dynamic updates and rendering.

Introduction to the component state

Each React component can also have what is known as a component state. The difference between a component’s properties and its state is that properties are set and managed by the parent component, but the state is managed by the component itself.

As an example of how we can use component state, let’s update our App component, and set an internal property that will toggle on or off when we click on our button.

To indicate that a React component has a state, we add a second argument to our component definition as follows:

Press + to interact
export interface IAppProps {}
export interface IAppState {
showDetails: boolean;
}
class App extends
React.Component<IAppProps, IAppState> {
constructor(props: IAppProps) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
showDetails: false,
};
}
render() {
return (
<div>
<p>showDetails ={this.state.showDetails ? "true" : "false"}</p>
<MyButton
buttonName="Click here"
handleButtonClick={this.handleClick}
></MyButton>
</div>
);
}
handleClick() {
console.log(`App.handleClick() called`);
this.setState({
showDetails: !this.state.showDetails,
});
}
}
export default App;

Here, we have made four changes to our App ...