All Projects → contiamo → react-connect-context

contiamo / react-connect-context

Licence: MIT license
A simple tool to map context from React 16.3's new Context API to a component's props.

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to react-connect-context

reactube-client
A clone Youtube Web Player using React Provider Pattern, React Context and Typescript
Stars: ✭ 92 (+142.11%)
Mutual labels:  react-context
React-Playground
Learning reactjs from the ground up (router, redux, thunk, hooks, context, portals, and functional components)
Stars: ✭ 15 (-60.53%)
Mutual labels:  react-context
react-context-example
Showcasing React Context
Stars: ✭ 34 (-10.53%)
Mutual labels:  react-context
Reworm
🍫 the simplest way to manage state
Stars: ✭ 1,467 (+3760.53%)
Mutual labels:  react-context
Constate
React Context + State
Stars: ✭ 3,519 (+9160.53%)
Mutual labels:  react-context
React-Combine-Provider
combine react providers in ease
Stars: ✭ 29 (-23.68%)
Mutual labels:  react-context
superhero
Convert a Redux app to React Context API App
Stars: ✭ 23 (-39.47%)
Mutual labels:  react-context
react-captain
⚓ A collection of strongly typed React hooks and contexts.
Stars: ✭ 15 (-60.53%)
Mutual labels:  react-context
react-emotion-multi-step-form
React multi-step form library with Emotion styling
Stars: ✭ 25 (-34.21%)
Mutual labels:  react-context
react-abac
Attribute Based Access Control for React
Stars: ✭ 54 (+42.11%)
Mutual labels:  react-context
react-magnetic-di
Dependency injection and replacement for React components and hooks
Stars: ✭ 103 (+171.05%)
Mutual labels:  react-context
react-multi-context
Manage multiple React 16 contexts with a single component.
Stars: ✭ 19 (-50%)
Mutual labels:  react-context

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<ContextValue, ContentProps>(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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].