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>
)
}
}
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:
Documentis an object. The global objectdocumentrepresents theHTMLdocument 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 asdocumentandwindowto interact with.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With