Tips for making reusable React components

Tip 1: props.children

const Picture = (props) => {
  return (
    <div>
      <img src={props.src}/>
      {props.children}
    </div>
  )
}
render () {
  return (
    <div className='container'>
      <Picture key={picture.id} src={picture.src}>
          //what is placed here is passed as props.children  
      </Picture>
    </div>
  )
}

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it and display using this.props.children (props.children for stateless components) .

This decouples the <Picture> component from its content and makes it more reusable.

Tip 2: Stateless Components

Stateless components are pure functions and hence, by default reusable.

Tip 3: Component Composition

Favor stateless component composition over component inheritance.




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *