Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access state value inside render method in reactjs

I'm new to react. Tried to pass state in constructor into my render method but My h1 is not visible, any clue what's wrong?

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };
       //this worked!
        document.title = this.state.title;
    }

    render() {
        return(
            <div>
                <h1>{this.title}</h1>
            </div>
        )
    }
}
like image 723
Jessica Robertson Avatar asked Dec 14 '25 21:12

Jessica Robertson


2 Answers

Reason is you are defining the title in state, treat state as an object, and all the variable that you defined inside that will be the key values, and to access them you have to use it like this: this.state.variable_name, Use this:

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };

    }

    render() {
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}

Reason why document.title='name' is working is, you are defining it as a global variable, and you can access them any where directly by document.title.

Doc:

Document is an object. The global object document represents the HTML document which is displayed in the current browser window. The web browser will have JavaScript engine. That engine will provide the developer with some runtime objects, such as document and window to interact with.

like image 123
Mayank Shukla Avatar answered Dec 16 '25 13:12

Mayank Shukla


It should be

class Mod extends React.Component {
    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };
    }

    componentDidMount() {
        document.title = this.state.title;
    }

    render() {
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}

Change document title in componentDidMount - it means it'll be executed when component is ready and visible.

You should not execute browser related actions in constructor as it might be called when there is no browser (eg. when you render your website using node.js server side rendering). componentDidMount will be only called when browser (and document) is available.

Also you need to use this.state.title instead of this.title. this relates to react component instance, this.state relates to state you've set in constructor.

like image 31
Adam Pietrasiak Avatar answered Dec 16 '25 14:12

Adam Pietrasiak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!