Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ways to Compose in React

Ways to Compose in React

React favors composition over inheritance. There are several useful ways to compose components in React.

Read more at: https://jaketrent.com/post/ways-to-compose-react-components/

510e0501c737af4df361f945fc295f63?s=128

Jake Trent

May 09, 2017
Tweet

Transcript

  1. WAYS TO COMPOSE IN REACT JAKE TRENT

  2. 1. WRAP CHILDREN 2. SPECIAL CHILDREN 3. VALUES AS PROPS

    4. COMPONENTS AS PROPS 5. OVERRIDE METHODS 6. HIGHER-ORDER COMPONENTS
  3. Wrap Children <Parent> <Child /> <Child /> </Parent> - Hierarchy

    - Style
  4. Special Children const SpecialChild = props => <div>{props.specialness}</div> const Parent

    = props => <div> {React.Children.map(props.children, child => child.type === SpecialChild ? React.cloneElement(child, { specialness: 'somethingFromParent' }) : child )} </div> - Nice APIs - Data sharing
  5. Values as Props const GiveMeValues = props => <div>{props.orGiveMe}</div> <GiveMeValues

    orGiveMe="death" /> - Dynamic values
  6. Components as Props const Title = _ => <h1>Composition!</h1> const

    SubTitle = _ => <div>Over Inheritance -- Literally</ div> const Header = props => <header> {props.title} {props.subtitle} </header> <Header title={<Title />} subtitle={<SubTitle />} /> - Dynamic UI - Component encapsulation
  7. Override Methods const defaultHandleClick = _ => alert('common clicked') const

    Common = props => <button onClick={props.handleClick ? props.handleClick : defaultHandleClick}>Click me</button> const overrideHandleClick = _ => alert('specific click') const Specific = _ => <Common handleClick={overrideHandleClick} /> - Dynamic functionality - Reuse common components
  8. Higher-order components const OriginalComponent = props => <div style={props.style}>Style me</div>

    const HigherOrder = newStyle => originalComponent => props => originalComponent({ ...props, style: { ...props.style, ...newStyle } }) const AlwaysRed = HigherOrder({ color: 'red' }) (OriginalComponent) - Share common functionality
  9. THANK YOU