0

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

2 Answers 2

3

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;
0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.