Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
stkvtflw Avatar asked May 12 '26 00:05

stkvtflw


1 Answers

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.

like image 116
Henrik Andersson Avatar answered May 14 '26 14:05

Henrik Andersson



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!