Reputation: 427
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>
)
}
}
Upvotes: 3
Views: 7698
Reputation: 21
If you need to get more values from state and those values are to be accessed in jsx many times then you can get like this.
class Mod extends React.Component {
constructor(props) {
super();
this.state = {
title : 'Hello world',
name: "john doe",
email: "[email protected]",
};
}
render() {
let { title, name, email } = this.state;
return(
<div>
<h1>{title}</h1>
<h1>{name}</h1>
<h1>{email}</h1>
<h1>{title}</h1>
<h1>{name}</h1>
<h1>{email}</h1>
<h1>{title}</h1>
<h1>{name}</h1>
<h1>{email}</h1>
</div>
)
}
}
Upvotes: 2
Reputation: 104369
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
.
Document
is an object. The global objectdocument
represents theHTML
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 asdocument
andwindow
to interact with.
Upvotes: 5
Reputation: 13184
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.
Upvotes: 4