How can a ReactJs component retrieve var from componentWillMount?
var React = require('react');
var SomeComponent = React.createClass({
componentWillMount: function() {
someVariable = "Variable";
return someVariable
},
render: function() {
return (
<div>{someVariable}</div>
);
}
});
module.exports = SomeComponent;
how can a component retrieve someVariable from componentWillMount?
source to share
Your example works because you are defining a global variable that the method can access render
. This is usually bad. What I think you are really after is setting this variable to the initial state of your component.
var SomeComponent = React.createClass({
getInitialState: function () {
return {someVariable: 'Variable'};
},
render: function () {
return <div>{this.state.someVariable}</div>
}
});
The setting state with this.setState
inside componentWillMount
is fine too, but will override whatever initial state your component has as it will only render once, so it makes sense to do it in getInitialState
if it's something that needs to be local to the component.
source to share
A typical example is using state via setState
. But if you have something that you need to set, your best bet is to pass it as a property. Another option is to add getInitialState
(although the documentation suggests this is an anti-pattern ).
If you want to do it in componentWillMount
, I would try this:
var SomeComponent = React.createClass({
componentWillMount: function() {
var someVariable = "Variable";
this.setState({someVariable: someVariable});
},
render: function() {
return <div>{this.state.someVariable}</div>;
}
});
It will work, but it will most likely generate a usage warning on a setState
lifecycle event, which is bad practice (I would rather use getInitialState
on top componentWillMount
for this particular instance).
source to share