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
2 Answers
Please follow this example. I have written a very simple component that will help you to understand state in react.
import React, {Component, useEffect, useState} from 'react';
class MyComponent extends Component {
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 <li key={i}>
{item}
</li>
})}
</div>
</div>
);
}
}
export default MyComponent;
An example of initializing state:
constructor(props) {
super(props);
this.state = {date: new Date()};
}
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.