How To Use State In React Project
I am new in react js. I want to know how to initialize state variable and how I can use state variable in html. Please help me how ever knows it. Thanks
Solution 1:
Please follow this example. I have written a very simple component that will help you to understand state in react.
importReact, {Component, useEffect, useState} from'react';
classMyComponentextendsComponent {
constructor(props) {
super(props);
this.state = {names: []};
}
componentDidMount() {
let json = [];
json.push("Taj");
json.push("Hamilton");
json.push("John");
this.setState({names: json});
}
render() {
return (
<div><div>
{this.state.names.map((item, i) => {
return <likey={i}>
{item}
</li>
})}
</div></div>
);
}
}
exportdefaultMyComponent;
Solution 2:
An example of initializing state:
constructor(props) {
super(props);
this.state = {date: newDate()};
}
This sets a property in the state called 'date', and initializes it with the current date.
To access it, you must render the HTML:
render() {
return (
<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>
);
}
This renders HTML which accesses the date
property on the state
object; specifically, the toLocaleTimeString()
function on the date object.
Source: the documentation, at https://reactjs.org/docs/state-and-lifecycle.html.
Post a Comment for "How To Use State In React Project"