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/

Jake Trent

May 09, 2017
Tweet

More Decks by Jake Trent

Other Decks in Programming

Transcript

  1. WAYS TO COMPOSE
    IN REACT
    JAKE TRENT

    View full-size slide

  2. 1. WRAP CHILDREN
    2. SPECIAL CHILDREN
    3. VALUES AS PROPS
    4. COMPONENTS AS PROPS
    5. OVERRIDE METHODS
    6. HIGHER-ORDER COMPONENTS

    View full-size slide

  3. Wrap Children




    - Hierarchy
    - Style

    View full-size slide

  4. Special Children
    const SpecialChild = props =>
    {props.specialness}
    const Parent = props =>

    {React.Children.map(props.children, child =>
    child.type === SpecialChild
    ? React.cloneElement(child, {
    specialness: 'somethingFromParent'
    })
    : child
    )}

    - Nice APIs
    - Data sharing

    View full-size slide

  5. Values as Props
    const GiveMeValues = props =>
    {props.orGiveMe}

    - Dynamic values

    View full-size slide

  6. Components as Props
    const Title = _ => Composition!
    const SubTitle = _ => Over Inheritance -- Literally
    div>
    const Header = props =>

    {props.title}
    {props.subtitle}

    } subtitle={} />
    - Dynamic UI
    - Component encapsulation

    View full-size slide

  7. Override Methods
    const defaultHandleClick = _ => alert('common clicked')
    const Common = props =>
    ? props.handleClick
    : defaultHandleClick}>Click me
    const overrideHandleClick = _ => alert('specific click')
    const Specific = _ =>

    - Dynamic functionality
    - Reuse common components

    View full-size slide

  8. Higher-order components
    const OriginalComponent = props =>
    Style me
    const HigherOrder = newStyle =>
    originalComponent =>
    props => originalComponent({
    ...props,
    style: { ...props.style, ...newStyle }
    })
    const AlwaysRed = HigherOrder({ color: 'red' })
    (OriginalComponent)
    - Share common functionality

    View full-size slide