2

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.

3
  • why not using state variable? if you don't use state and setState then your component will not get re-rendered and msg part will not update in ui. Commented Jun 8, 2017 at 20:47
  • You should set that on the state with setState function.. Also, createClass is deprecated. Commented Jun 8, 2017 at 20:47
  • thanks for the suggestions.. Commented Jun 8, 2017 at 20:52

1 Answer 1

2

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='';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.