Published on

Using other components in a custom React component

Authors

While cleaning up some code today I found a bunch of repeated boiler plate HTML fragments that I wanted to extract out into a common component. The problem was that one of the parts of the component that changes was itself a React component.

<div className="someClass">
  <div className="control">
    <label>Name</label>
    <input
      type="text"
      placeholder="Type your name and middle name here"
      value={this.state.name}
      onChange={this.verifyName}
      type="text"
    />
  </div>
  ...
  <div className="control">
    <label>Age</label>
    <input
      type="text"
      placeholder="Type your name and middle name here"
      value={this.state.age}
      onChange={this.verifyAge}
      type="number"
    />
  </div>
</div>

I wanted to extract the above to a component that would hide away the boiler plate and allow something like:

<MyCustomComponent label="name">
  <input
    type="text"
    placeholder="Type your name and middle name here"
    value={this.state.name}
    onChange={this.verifyName}
    type="text"
  />
</MyCustomComponent>

I tried by passing the other React component as a prop and just calling it as you would a function prop.myOtherComponent() but that did not work. I thought it may work as React treats components as functions.

After some Googling I discovered that referring to elements surrounded by a custom component is trivial. You simply refer to nested components using props.children:

render(props) {
   return (<div className="control">
        <label>{props.label}</label>
        {this.props.children}
    </div>
 )
}

More on this can be found here.