stkvtflw
stkvtflw

Reputation: 13537

How ReactJs component could 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 component could retrive someVariable from componentWillMount?

Upvotes: 3

Views: 1295

Answers (2)

Cymen
Cymen

Reputation: 14419

The typical pattern is to use state via setState. But if you have something you need to set, the best thing is to pass it in as a property. Another option is to add a 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'll likely generate a warning about using setState in a lifecycle event and it's a bad practice (I'd prefer to use getInitialState over componentWillMount for this specific instance).

Upvotes: 2

Henrik Andersson
Henrik Andersson

Reputation: 47182

Your example works because you're defining a global variable that the render method then can access. This is typically bad. What I think you're really after is setting this variable on the initial state of your component.

var SomeComponent = React.createClass({
   getInitialState: function () {
      return {someVariable: 'Variable'};
   },
   render: function () {
      return <div>{this.state.someVariable}</div>
   }
});

Setting state with this.setState within componentWillMount is fine as well but will override any initial state your component has since the render will still only execute once therefore it makes more sense to do it within getInitialState if it's something that's supposed to be local to the component.

Upvotes: 5

Related Questions