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

Ways to Compose in React

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →

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/

Jake Trent

May 09, 2017

Transcript

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

    4. COMPONENTS AS PROPS 5. OVERRIDE METHODS 6. HIGHER-ORDER COMPONENTS
  2. 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
  3. 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
  4. 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
  5. 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

More Decks by Jake Trent

Other Decks in Programming