I have a form with state handled in a context. within the form I have a checkbox component which I am trying to have its state handled within the context. So when I submit the form the checkbox returns a Boolean whether it is checked or not. I'm having trouble with the event handler triggering the checkbox.
I have a number of textfields in the form which are behaving as expected and their values can be seen in the Db once the form is submitted.
Within the checkbox component the actual input is hidden for styling purposes. So the user will be clicking on the label(which is styled to look like a checkbox) or a secondary label (acting as a label)
I'd like it so that when a user clicks on either of the labels the checkbox is triggered. I had the onClick on the checkbox input but seeing as it's display is hidden the user cannot trigger the event.
If I put the onClick on either of the labels or a parent element my onChange functions e.target is pointing to the wrong location.
Is there a way to pass in the the input as the e.target? if the onClick event is on the outer div?
onChange (within RecordForm.js)
const onChange = (e) => {
setRecord({ ...record, [e.target.name]: e.target.value });
};
Checkbox.js
const CheckBox2 = ({ value, label, name, onChange }) => {
return (
<CheckBoxContainer onClick={onChange}>
<LabelContainer>
<CheckboxInput
type='checkbox'
value={value}
name={name}
/>
<CheckBoxLabel>
<Tick className='Tick' />
</CheckBoxLabel>
</LabelContainer>
<VisibleLabel>{label}</VisibleLabel>
</CheckBoxContainer>
);
};
export default CheckBox2;
question from:
https://stackoverflow.com/questions/65644176/how-to-trigger-an-onclick-event-in-react-from-a-parent-component-to-trigger-its 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…