react-connect-context
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

react-connect-context

Tiny Build Status Coverage Status

With some of our internal applications at Contiamo, the render-prop–style API of React 16.3's new Context API proves to be a bit limiting: particularly the inability to use a consumed context value in component lifecycle hooks. One solution to this is to pass an object through context, and then through props.

Instead of repeatedly writing "context containers" that pass context objects to container components through props that further pass state to presentational components through props, this tiny function allows us to give any component easy access to a created context through props, allowing for more idiomatic, predictable code.

If a component has a prop that collides with a context-passed-through prop, the component's prop has precedence. Simple.

Try it out!

Getting Started

  1. yarn add react-connect-context
  2. At the top of your file, import { connectContext } from "react-connect-context"
  3. Wrap your component in the function as so: connectContext(Context.Consumer)(MyComponent)

Full Example

Edit react-connect-context demo

import React from "react"
import { render } from "react-dom"
import { connectContext } from "react-connect-context"
 
// CHANGE ME TO CHANGE THE CONTEXT FOR THE WHOLE APP!
const COLOR_PASSED_THROUGH_CONTEXT = "red"
 
interface ContextValue {
    color: string;
}
 
interface ContentProps {
    myProp: string;
    color: string;
}
 
class App extends React.Component {
  render() {
    return (
      <div className="demo">
        <Header>Welcome to my App!</Header>
        <ConnectedContent myProp="THIS IS MY PROP, HI!" >
          Hello! I've written this component so that Magical Context-based text appears after children!
        </ConnectedContent>
      </div>
    )
  }
}
 
// Presentational, nested components
const Header: React.SFC = ({ children }) => <h1>{children}</h1>
const Content: React.SFC<ContentProps= ({ children, color, myProp }) => (
  <div>
    <p>{children}</p>
    <div>
      I have looked into context and I've seen the color is:
      <span style={{ color }}>
        <strong>{color}</strong>
      </span>! I also get my own props like <strong>{myProp}</strong>!
    </div>
  </div>
)
 
// Make a context.
const Context = React.createContext<ContextValue>({ color: "red" })
 
// Pass the consumer to our function.
const ConnectedContent = connectContext<ContextValueContentProps>(Context.Consumer)(Content)
 
// Render things, wrapping all in the provider.
render(
  <Context.Provider value={{ color: COLOR_PASSED_THROUGH_CONTEXT }}>
    <App />
  </Context.Provider>,
  document.querySelector("#root")
)

Frequently Asked Questions

Can I pick state and only re-render when necessary?

Sure. Consider using PureComponent or shouldComponentUpdate to let your components know when or when not to update.

Additionally, unlike Redux, React 16.3 allows the creation of multiple, composable Contexts, so ideally, you'd be using a Context that is small enough to house just the information that you'd like to reuse in order to properly separate concerns and correctly use the principle of least privilege when passing context around.

Can I map my context object's properties to different props on my component?

For now, no. This particular tool is designed to provide a nice cascade of props: if a component has a prop on it, like color from the above example, that prop is used. If it doesn't have a prop, but the prop exists on a Context, its prop is used.

I would again toot the horn of using multiple small contexts here as above.

Gotchas

The Context value has to be an object since it maps to props by key/value pairs. Be careful if your context is just a string, as in the basic example from React's RFC. This will throw an error that will lead you here. :)


Made with ❤️ at Contiamo in Berlin.

Readme

Keywords

none

Package Sidebar

Install

npm i react-connect-context

Weekly Downloads

59

Version

1.1.0

License

MIT

Unpacked Size

10.2 kB

Total Files

8

Last publish

Collaborators

  • tejaskumar