I have a component that renders labels, and I pass the input elements as children as follows:
<FormGroup labelFor="my-formgroup-id">
<input id="my-formgroup-id" /> // I don't want to duplicate this id manually here but take it from the `labelFor prop of the `<FormGroup>` it's wrapped in
</FormGroup>
How do I take that id
prop/value from FormGroup
and access it in the <input>
?
I need the FormGroup component to render the labels and validation errors, and only want to pass different kinds of inputs (input, textarea, etc.) as children to it. However, of course the labels inside FormGroup has a for
attribute to focus the right input when a corresponding label is clicked. So that's why both FormGroup and the input passed as a child element needs to know the same id.
Also I'm using functional components instead of class based.
This is what <FormGroup>
looks like:
const FormGroup = (labelFor, children) => {
<label for={labelFor}></label>
{children}
}