npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-zap

v2.1.0

Published

Zap props from a component to another, using the new context API!

Downloads

2,572

Readme

npm version License: MIT Build Status styled with prettier

react-zap

:zap: Zap props from one React component to another! :zap:

Why?

React's new context API allows you to send data from one component to any component in its tree of children. React-zap lets you tie this powerful new feature in to the similarly powerful concept of higher-order components!

HoCs and Render Props?

One aspect of the new context API which has been much talked about in the community is that it uses the function-as-a-child pattern (also called render props) for its Consumers. This pattern has been positioned by some as an alternative to higher-order components, so the general impression is that you need to choose: either use HoCs or use Render Props.

However, the API is about sharing dynamic context, not about render functions. The ability to pass data directly to any child is applicable to many situations; the method with which you access this data is not relevant to the feature. And in fact, this feature can be combined with higher-order components to make it even more powerful!

HoCs are not dead! This package allows you to use your trusted and useful HoCs and to plug them into React's new context API.

This package offers two higher-order components: propsToContext to populate a context provider with existing props, and contextToProps if you prefer to consume context with a HoC (for example within a compose function).

API

:zap: propsToContext(Provider, config?)(BaseComponent)

Wraps your component with the specified Provider, and sends the component's props into context. By default, all props will be included in context; you can optionally define a list of props to include, or a function to map the props manually.

  • Provider: a React context provider, returned by React.createContext
  • config:
    • An array of prop keys to sent to context.

      Example: propsToContext(Provider, ['propToInclude'])(Component)

    • A function mapping props to context.

      Example: propsToContext(Provider, ({ propToIgnore, ...otherProps }) => otherProps)(Component)

:zap: contextToProps(Consumer, config?)(BaseComponent)

Wraps your component with the specified Consumer, and sends the context into its props. By default, the context will be spread into the component's props; you can optionally define a prop key for the context object, or a function to map to props manually.

  • Consumer: a React context consumer, returned by React.createContext
  • config (optional):
    • A string, to be used as a prop key for the context object.

      Example: contextToProps(Consumer, 'allContext')(Component)

    • A function mapping context to props.

      Example: contextToProps(Consumer, ({ contextToIgnore, ...otherContexts }) => otherContexts)(Component)

Examples

With a state HOC

Using react-state-hoc. We will first create our context components:

import React from 'react'

const initialState = {
    visible: false
}

const {
    Provider: StateProvider,
    Consumer: stateConsumer
} = React.createContext(initialState)

export { initialState, StateProvider, StateConsumer }

Given an imaginary ViewComponent, we will set our state in context using propsToContext. Note the use of a compose function to compose our different higher-order components, provided by some libraries like redux (you can write your own!)

import React from 'react'
import { withState } from 'react-state-hoc'

import { initialState, StateProvider } from './context'
import ViewComponent from './ViewComponent'

export default compose(
    withState(initialState, {
        setVisibility: visible => ({ visible })
    })
    propsToContext(StateProvider, [ 'visible', 'setVisibility' ])
)(ViewComponent)

Now the state in withState will be added to our provider. Note that we have whitelisted props 'visible' and 'setVisibility'. To consume it, given ToggleButton and Toggle components mounted somewhere deep in ViewComponent:

import React from 'react'
import { contextToProps } from 'react-zap'
import { StateConsumer } from './context'

const withState = contextToProps(StateConsumer)

const ToggleButton = ({ setVisibility }) => (
    <button onClick={() => setVisibility(!visible)}>
        Toggle
    </button>
)

const Toggle = ({ visible }) => visible ? <div>Hello</div> : null

export {
    ToggleButton: withState(ToggleButton),
    Toggle: withState(Toggle)
}

With render functions instead of contextToProps HoC:

import React from 'react'
import { StateConsumer } from './context'

export function ToggleButton() {
    return (
        <StateConsumer>
            {({ visible, setVisibility }) => (
                <button onClick={() => setVisibility(!visible)}>Toggle</button>
            )}
        </StateConsumer>
    )
}

export function Toggle() {
    return (
        <StateConsumer>
            {({ visible, setVisibility }) =>
                visible ? <div>Hello</div> : null
            }
        </StateConsumer>
    )
}

With redux connect

The same logic applies with a higher-order component like connect from the react-redux package:

import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import ViewComponent from './ViewComponent'
import ViewChild from './ViewChild'

const { Provider, Consumer } = React.createContext()

// Set context for any component in `ViewComponent`
// All props received by `propsToContext` will be set to `Provider`,
// including what is returned by `mapStateToProps` and `mapDispatchToProps`
const ViewContainer = compose(
    connect(mapStateToProps, mapDispatchToProps),
    propsToContext(Provider)
)(ViewComponent)

// No we can consume our context in any descendant!
const ViewChild = () => <Consumer>{context => <div />}</Consumer>