Anpu Ann John
Anpu Ann John's Blog

Anpu Ann John's Blog

React Class Components #4

Anpu Ann John's photo
Anpu Ann John
·Dec 21, 2020·

2 min read

Another way to materialize the JSX component is by using class-based components other than functional components.

*Why we use class-based components over functional components?

The state is the data that the component maintains. It can change the value, unlike props. For using state, the component should be class-based*

Screenshot (15).png

This is an example of a simple class-based component. First, we import the component class from the react package. Use the keyword "extends" to import the properties of React. Component in our class.Render() method helps to display the content to the browser.

Using State:

Screenshot (16).png

The value of the state is rendered to the screen. Add a constructor method to initialize the class. Make a call to the superclass (react component). Add properties and values to this. state object.

Changing State:

If we are not able to change the state, it is almost the same as hard coding the values. To change state, we use this.setState() method inside an event handler. To let the react know the event handler method will change the state of the value we bind them inside the constructor.

Screenshot (20).png

Right now, the event handler is not able to remember its previous state. Modify the event handler, If we want to change the value of properties back and forth.

Screenshot (22).png

In case if we need to Increment the value of a state variable with the click of a button. Modify the event handler ..

Screenshot (21).png

☺️☺️☺️☺️☺️ ☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️ ☺️☺️☺️☺️☺️ ☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️☺️

Share this