Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  66] [ 2]  / answers: 1 / hits: 47964  / 9 Years ago, sat, january 2, 2016, 12:00:00

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



enter



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?


More From » checkbox

 Answers
40

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


[#63870] Wednesday, December 30, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sidneyh

Total Points: 118
Total Questions: 108
Total Answers: 105

Location: Mali
Member since Fri, Jun 18, 2021
3 Years ago
sidneyh questions
Tue, Jun 7, 22, 00:00, 2 Years ago
Wed, Apr 13, 22, 00:00, 2 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Fri, Apr 24, 20, 00:00, 4 Years ago
;