1.0.5 • Published 5 years ago

react-better-context v1.0.5

Weekly downloads
15
License
ISC
Repository
github
Last release
5 years ago

React better context

React's context is awesome, but a pain on jsx, having a couple of contexts applied to a component makes more spaghetti than my italian mother.

Before

default

After

better

Install

A version of react >= 16.3 is required for this package, as it contains the final context specs.

npm i react-better-context

How to use

The default export createContext is a function requiring a minimum of 2 paramethers, the name that will be used to display the context container (string), and the default value of the context.

// userContext.js
import createContext from "react-better-context";

const UserContext = createContext("User", { name: "kornil" });

UserContext value is an object containing Provider, the default context provider, and a connect function that is used to link the consumer instead of the context Consumer.

import UserContext from "./userContext.js"

// connecting the Provider
class BigContainer extends react.Component {
...
  render() {
    const properContextValue = {
      hello: "world",
      name: "kornil"
    }
    return (
      <UserContext.Provider value={properContextValue}>
        <MyComponent />
      </UserContext.Provider>
    )
  }
}

// connecting the Consumer
const MyComponent = (props) => (
  <h1>
    hello {props.UserContext.name}
  </h1>
);

export UserContext.connect(MyComponent);

And you're done.

TL;DR Use Provider the same && instead of Consumer in your jsx, use the connect function the same as react-redux.

Info

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago