Simple. First you must always bear in mind that in React you work with controlled elements , that is, elements that will be controlled by the React status to change and / or mutate. That said, it's really simple.
Have in your state Boolean values for each checkbox (true | false). Now, for each checkbox you must assign the same event, say onCheck
and pass it as a parameter, the name of the checkbox . Within this method you update the status by changing the value true
or false
for that checkbox and at the same time, putting the rest of the checkboxes as false
.
Example
class CheckBoxExample extends React.Component {
constructor(props) {
super(props);
this.state = {
checkboxes: {
c1: false,
c2: false,
c3: false,
selected: null,
},
};
}
onCheck(name, val) {
const checkboxes = Object.assign({},this.state.checkboxes, {});
for (let key in checkboxes) {
checkboxes[key] = false;
}
checkboxes[name] = true;
checkboxes.selected = val;
this.setState({ checkboxes });
}
render() {
return (
<div>
<label>Seleccionado: {this.state.checkboxes.selected}</label><br />
C1 <input
type="checkbox"
value="c1"
checked={this.state.checkboxes.c1}
onChange={(e) => this.onCheck('c1', e.target.value) }
/>
C2 <input
type="checkbox"
value="c2"
checked={this.state.checkboxes.c2}
onChange={(e) => this.onCheck('c2', e.target.value) }
/>
C3 <input
type="checkbox"
value="c3"
checked={this.state.checkboxes.c3}
onChange={(e) => this.onCheck('c3', e.target.value) }
/>
</div>
);
}
}
const node = document.getElementById('root');
ReactDOM.render(<CheckBoxExample />, node);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>