What is Stateful/Class based Component in ReactJS ?
Last Updated :
28 Nov, 2023
React class-based components, essential for many modern ReactJS web apps, are simple classes extending React’s Component class, incorporating multiple functions to enhance application functionality. Once declared, these components can be utilized in other components.
Prerequisite:
Steps to Create the React Application And Installing Module:
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 :
cd foldername
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example 1: Class components in React have a distinctive feature known as “state,” representing an object with observable properties that control the component’s behavior. The state holds information that can change during the component’s lifespan, and it’s managed using the `setState()` function. This allows modification of one or more variables, arrays, or objects within the state.
Javascript
import React from "react" ;
class App extends React.Component {
render() {
return <h1> Welcome to GeeksForGeeks</h1>;
}
}
export default App;
|
Step to run the application: Open the terminal and type the following command.
npm start
Output:
Example 2: Props in React class components facilitate data transfer between components, always passed from parent to child. Components can’t modify their props directly; changes are made by altering props in the parent component and passing them down. Accessing props within a class component is done using `this.props`, where prop names act as keys in the `this.props` object.
Javascript
import React from "react" ;
class App extends React.Component {
constructor(props) {
super (props);
this .state = { change: true };
}
render() {
return (
<div>
<button
onClick={() => {
this .setState({ change: ! this .state.change });
}}
>
Click Here!
</button>
{ this .state.change ? (
<h1>Welcome to GeeksforGeeks</h1>
) : (
<h1>A Computer Science Portal for Geeks</h1>
)}
</div>
);
}
}
export default App;
|
Output:
Share your thoughts in the comments
Please Login to comment...