Mohammad Tanveruzzaman
Mohammad Tanveruzzaman

Reputation: 199

how to pass variable from a function to render function in react

I am new in react. following a tutorial, where they are introducing state to find out wheather checkbox is checked or not. But i wanted to do that in this style:

<script type="text/babel">
  var Checkbox = React.createClass({
    change: function(){
      var msg;
      var val= document.getElementById('check').checked;
      if(val==true){
        msg = 'checked';
      }else{
        msg = 'Not checked';
      }
    },
    render: function(){
      return(<div>
          <input onChange={this.change} id="check" type="Checkbox" />
          <p>Checkbox is {this.msg}.</p>
        </div>);
    }
  });
  ReactDOM.render(<Checkbox/>, document.getElementById('container'));
</script>

so, the problem is i cant pass the variable "msg" into render function.

Upvotes: 2

Views: 3962

Answers (1)

Kavita
Kavita

Reputation: 51

If you want to render the message in UI, then msg should be set in state using setState function, so that re-render can happen.

For any other case where re-render is not required, variable can be created as class variable inside constructor and use in any function.

constructor(props){
super(props);
this.myVariable='';
}

Upvotes: 2

Related Questions