States in Class
- State in React is an object that holds values that can change over time. It is same as member variable in class.
- The state can be updated using the setState() method, which triggers a re-render of the component and its children.
- The state should only be modified using setState() and should not be directly mutated.
- Accessing and rendering state values in a component’s UI is done using curly braces ({}) within JSX.
We have created constructor in class to have initial state. in the below example there are 2 state: age and address.
the áge’state has been accessed like {this.state.age}
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import React,{Component } from 'react'; import ReactDOM from 'react-dom/client'; //Person class component class Person extends Component { constructor(){ super(); this.state ={ age: 30, address: "India" } } render() { return ( <div>My name is Shrikant from Person class component and age is {this.state.age}</div> ) } } //App function component function App() { return ( <div> <h1>Hello, World!</h1> <p>This is a example of class component in JSX.</p> <Person/> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
Output:
Hello, World!
This is a example of class component in JSX.
My name is Shrikant from Person class component and age is 30
_____________________________________________________________
2) States in functional components is implemented using the useState hook.
which we will discuss in hook tutorial.