Child Component Making Use of Parents' Prop in ReactJS

Child Component Making Use of Parents' Prop in ReactJS
0

I am creating a form Component that will have a Form component and an Input component. Something like this:

<Form>
  <Input name="name" />
  <Input name="email" />
</Form>

In my setup, labels are automatically get generated from the name prop. What I would like to do, though, is provide an option to not show labels. Now, I could do it on each <Input> component like this:

<Form>
  <Input noLabel name="name" />
  <Input noLabel name="email" />
</Form>

But what I would really like to do is add it to the <Form> component and have it automatically applied to each <Input> component. Something like this:

<Form noLabel>
  <Input name="name" />
  <Input name="email" />
</Form>

The way I envision it, when defining my <Input> component I could do a check if the noLabel prop is set on the <Form> component. Something like this:

export const Input = props => {
  ...
  {!props.noLabel && <label>...}
  <input.../>
  ...
}

But I can’t figure out how to get access to the noLabel prop from the <Form> component so that I can check to see whether or not it is set.

Any ideas on how to do this?

Note that this is generally an antipattern as you’re explicitly coupling the components: you’re using inheritance, which React is not really designed for, and it will complicate your code (so just take care that you actually need to do this and aren’t overabstracting things), but:

const Form = ({ nolabel, children }) => (
  <form>
    { React.cloneElement(children, { nolabel }) }
  </form>
);

You can’t adjust the props of children directly, as they are immutable, but you can clone them and attach props to the clones.