0.2.1 • Published 6 years ago

react-controllers v0.2.1

Weekly downloads
168
License
MIT
Repository
-
Last release
6 years ago

react-controllers

Utilities for working with React controller components.

npm version

npm install react-controllers --save

React Controllers

A controller is a term for a React components that follow three rules:

  • It expects to receive a render function via its children prop
  • It passes an output object to that render function
  • It does not define shouldComponentUpdate or PureComponent

For example:

render() {
  return (
    <AuthController>
      {output =>
        <div className="identity">{output.name}</div>
      }
    </AuthController>
  )
}

Some common controllers include the <Consumer> component of React's Context API, and the <Route> component from react-router 4.

<Combine>

When composing a number of controllers, you'll encounter the controller mountain problem: whitespace starts stacking up in a way reminiscent of callback pyramids.

<AuthController>
  {auth =>
    <NavContext.Consumer>
      {nav =>
        <StoreContext.Consumer>
          {store =>
            <MyScreen auth={auth} nav={nav} store={store} />
          }
        </StoreContext.Consumer>
      }
    </NavContext.Consumer>
  }
</AuthController>

The <Combine> controller solves this by combining controllers together.

Each prop for <Combine> should be a function that returns a controller element. It then threads the outputs of each controller into the output of its own children function. For example, the above could be rewritten as:

import { Combine } from 'react-controllers'

<Combine
  auth={children => <AuthController children={children} />}
  nav={children => <NavContext.Consumer children={children} />}
  store={children => <StoreContext.Consumer children={children} />}
>
  {output =>
    <MyScreen {...output} />
  }
</Combine>