1.1.0 • Published 5 years ago

react-context-consumer v1.1.0

Weekly downloads
4
License
MIT
Repository
github
Last release
5 years ago

ci codecov downloads node npm MIT npm bundle size

react-context-consumer

Small and lightweight context consumer for your class-components

Overview

With new Context API to consume several contexts we need to put several context consumers in our component (one for each context):

import React, { Component } from 'react';

class MyComponent extends Component {
    render() {
        return (
            <ThemeContext.Consumer>
                {theme => (
                    <LocaleContext.Consumer>
                        {locale => (
                            <StorageContext.Consumer>
                                {storage => (
                                    // render component using theme, locale and storage
                                )}
                            </StorageContext.Consumer>
                        )}
                    </LocaleContext.Consumer>
                )}
            </ThemeContext.Consumer>
        );
    }
}

react-context-consumer helps to simplify render() function in such situations. Just pass several contexts into contexts prop and consume all of them at once:

import React, { Component } from 'react';
import ContextConsumer from 'react-context-consumer';

class MyComponent extends Component {
    render() {
        return (
            <ReactContextConsumer contexts={[ ThemeContext, LocaleContext, StorageContext ]}>
                {(theme, locale, storage) => {
                    // render component using theme, locale and storage
                }}
            </ReactContextConsumer>
        );
    }
}

I guess, it looks nicer =)

Additional arguments for renderProp function

Let's imagine we already have a component using react context consumers and custom render prop with additional arguments like this one:

class CustomComponent extends React.Component {
    ...

    renderComponent(someValue) {
        return (
            <ThemeContext.Consumer>
                {theme => (
                    <LocaleContext.Consumer>
                        {
                            locale => this.renderComponentWithContext(theme, locale, someValue)
                        }
                    </LocaleContext.Consumer>
                )}
            </ThemeContext.Consumer>
        )
    }

    renderComponentWithContext(theme, locale, someValue) {
        ...
    }
}

You can now just pass all needed additional arguments using args prop:

class CustomComponent extends React.Component {
    ...

    renderComponent(someValue) {
        return (
            <ContextConsumer contexts={[ ThemeContext, LocaleContext ]} args={[ someValue ]}>
                {this.renderComponentWithContext}
            </ContextConsumer>
        )
    }

    ...
}
1.1.0

5 years ago

1.0.0

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago