- React State is an inbuilt object of Rect Component
- React State is that object Where we store the properties of React component value
- Changing in React State re rendering take place
Whare is React State is initialize ?
React State is initialize in React Component Constructor
Example
class Name extends React.Component {
constructor(props) {
super(props);
this.state = {name: "yashpal"};
}
render() {
return (
<div>
<h1>My name</h1>
</div>
);
}
}
Multiple Properties in React State we can store
Example
class Name extends React.Component {
constructor(props) {
super(props);
this.state = {
name1: "yashpal",
name2: "christo"
};
}
render() {
return (
<div>
<h1>All names</h1>
</div>
);
}
}
How to use React State in Component ?
Syntax
this.state.propertyname
Example
class Name extends React.Component {
constructor(props) {
super(props);
this.state = {
name1: "yashpal",
name2: "christo",
name3: "killian",
name4: "thanos"
};
}
render() {
return (
<div>
<h1>My name is {this.state.name1}</h1>
<h2>
my second name is {this.state.name2}
</h2>
</div>
);
}
}
What is setState() in react Component ?
setState() is used to change the properties of React Component State properties
Example
class Name extends React.Component {
constructor(props) {
super(props);
this.state = {
name1: "yashpal",
name2: "christo"
};
}
changeName= () => {
this.setState({name2: "killian"});
}
render() {
return (
<div>
<h1>My name is {this.state.name1}</h1>
<h2>my another name is {this.state.name2} </h2>
<button
type="button"
onClick={this.changeName}
>Change name</button>
</div>
);
}
}
Output:
After click my another name christo will get change to killian