Ad

React: Get Custom Checkbox's Checked Attribute

- 1 answer

I want to so some customization with checkbox, it can look like this:

enter image description here

so I wrap my custom checkbox into a React Component:

require('../../less/ck-checkbox.less');
var React = require('react');

var CkCheckbox = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
    text: React.PropTypes.string,
    defaultChecked: React.PropTypes.bool,
    onChange: React.PropTypes.func
  },
  getDefaultProps: function() {
    return {
      name: 'checkbox',
      text: '',
      defaultChecked: false,
      onChange: function () {}
    };
  },
  render: function() {
    return (
      <div className="ck-checkbox">
        <label>
          <input
            type="checkbox"
            name={this.props.name}
            ref="c"
            defaultChecked={this.props.defaultChecked}
            onChange={this.props.onChange.bind(this, this.refs.c.checked)}
          />
            <span className="icons">
              <span className="icon-checked-o icon-true"></span>
              <span className="icon-circle-o icon-false"></span>
            </span>
            {this.props.text.length > 0 ?
              <span className="ck-checkbox-text">{this.props.text}</span> : null
            }
          </label>
        </div>
      );
    }
});

module.exports = CkCheckbox;

and my container is like this:

var React = require('react');

var CkCheckbox = require('./CkCheckbox.js');

var Test = React.createClass({
  render: function() {
    return (
      <div>
        <CkCheckbox onChange={this._handleChange}/>
      </div>
    );
  },

  _handleChange: function(checked, e) {
    console.log(checked)
  }
});

module.exports = Test;

you can see that, I tried to bind this.refs.c.checked in the onChange callback, but it doesn't work.

so, how can I get the checked state of my custom checkbox in Test component in the _handleChange function?

Ad

Answer

In this case you don't need use refs because you can get checked property from e argument

// CkCheckbox component
 <input type="checkbox" 
     name={this.props.name} 
     defaultChecked={this.props.defaultChecked} 
     onChange={ this.props.onChange } />

// Test component
_handleChange: function(e) {
  var checked = e.target.checked;
  console.log(checked)
}

Example

or if you want pass only checked property you can do it like this

// CkCheckbox component
handleChange: function (e) {
  this.props.onChange(e.target.checked);
},

<input type="checkbox" 
   name={this.props.name} 
   defaultChecked={this.props.defaultChecked} 
   onChange={ this.handleChange } />

// in Test component 
_handleChange: function(checked) {
  console.log(checked)
}

Example

Ad
source: stackoverflow.com
Ad