Reputation: 110970
I have the following render for a React.Component:
<div>
<input
type="checkbox"
id={`checkbox-${name}`}
name={name}
checked={checked}
disabled={disabled}
onChange={onChange}
onBlur={onBlur}
onFocus={onFocus}
/>
<label htmlFor={`checkbox-${name}`}>
<image alt="Checkmark" src={checkmarkSvg} />
</label>
</div>
When I click the label, I see the checkbox input flash but not get selected... I need the formatting above as I'm hiding the input and using the label to render a custom css3 checkbox style.
Why isn't clicking the label checking the input type checkbox?
Upvotes: 2
Views: 2382
Reputation: 2738
The reason why it doesn't change is because you are setting its value checked
to checked
in your react component. However, what you are not doing is onChange of the component updating the value of checked
so that the component reflects this. The input has a controlled state, which mean you have to control it. Below is an example of this implemented and used:
constructor(props) {
super(props);
this.state = { checked: false };
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({ checked: e.target.checked });
}
render() {
const { checked } = this.state;
return (
<input
type="checkbox"
id={`checkbox-${name}`}
name={name}
checked={checked}
onChange={this.onChange}
/>
);
}
Upvotes: 2