1

I have this code in Reactjs that display a label with a checkbox

import React, { Component, PropTypes } from 'react';


class Test extends Component {
  constructor() {
      super(...arguments);
  }

  checkboxClicked(e) {
      this.props.test.clicked = e.target.checked;
  }

  render() {
    return (
        <li>
            <label>

                <input type="checkbox" value={this.props.test.id} checked={this.props.test.clicked} onChange={this.checkboxClicked.bind(this)} />
                {this.props.test.text}

            </label>
        </li>
    );
  }
}

export default Test;

The checkbox and text is well displayed, but when I click on it, it refused to get checked. The value of this.props.test.clicked is changed but not the ui in the browser.

Can somebody tell me that I am missing?

4
  • Can you provide a live example reproducing the problem? Commented Oct 7, 2016 at 15:41
  • Here is a live example jsfiddle.net/2kctv533 Commented Oct 7, 2016 at 16:26
  • The component is never rerendered because the state never changes. Use state, not props. Commented Oct 7, 2016 at 16:35
  • @AndrewL.It might not be the right way to do so, but in the parent components, I use the props value to find which checkbox was checked... In your method, how can I know which Test was checked? Commented Oct 7, 2016 at 16:36

1 Answer 1

1

It's not recommended to change props. Try to use state instead.

import React, { Component, PropTypes } from 'react';


class Test extends Component {
  constructor() {
      super(...arguments);

      this.state = { checked: this.props.test.clicked };
  }

  checkboxClicked(e) {
      this.setState({checked : e.target.checked});
  }

  render() {
    return (
        <li>
            <label>

                <input type="checkbox" value={this.props.test.id} checked={this.state.checked} onChange={this.checkboxClicked.bind(this)} />
                {this.props.test.text}

            </label>
        </li>
    );
  }
}

export default Test;
Sign up to request clarification or add additional context in comments.

2 Comments

It might not be the right way to do so, but in the parent components, I use the props value to find which checkbox was checked... In your method, how can I know which Test was checked?
Can you show me your parents components who need to test if those checkbox are checked ?

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.