What is Stateful/Class based Component in ReactJS ?
React class-based components: These are the bread and butter of most modern web apps built in ReactJS. These components are simple classes (made up of multiple functions that add functionality to the application). All class-based components are child classes for the Component class of ReactJS. Once a component is declared, it can be used in other components.
Create React app:
Step 1: execute Create react app using the following command.
npx create-react-app foldername
Step 2: Change directory to that folder by executing the command :
Project Structure: It will look like the following.
Example 1: Program to demonstrate the creation of a class-based component.
Step to run the application: Open the terminal and type the following command.
State in class components: The main feature of class-based components that distinguishes them from functional components is that they have access to a state which dictates the current behavior and appearance of the component. The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state. We will look into this more elaborately later in the article. This state can be modified by calling the setState() function. One or more variables, arrays, or objects defined as part of the state can be modified at a time with the setState() function.
Example 2: Program to demonstrate the use of state and props in class-based components. Open the App.js file and replace the code with the below code.
Props in class components: Data is passed to other components with the help of props. Props work similarly for all components in ReactJS be they class-based or functional. Props are always passed down from the parent component to the child component. ReactJS does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed from the parent component to the child component. This is generally done by passing a reference to a function in the parent component, which changes the props being passed to the child component. We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of the components props. The propName, that is the names of props are keys of this object.
Example 3: Program to demonstrate the use of props in class-based components. Open the App.js file and replace the code with the below code.
Please Login to comment...