Redux's Provider Component

(Pssssst! All the code referenced in this post can be found at https://github.com/NerdcoreSteve/ReduxProvider)

Hey all, when I did a post about React and Redux, I didn't mention something that you'll probably want to use: Redux's Provider component.

It's a helper React component that eliminates the need to keep passing along the redux store as a parameter. Here's how I'm using it in my example code:

.....
    {Provider} = require('react-redux'),
.....
    render = () =>
        ReactDOM.render(
            <Provider store={store}>
                <div>
                    <TypeyThing/>
                    <ListOfThings/>
                </div>
            </Provider>,
            document.getElementById('root'))

Provider is a component you can get from the react-redux module. It can only have one child component so I wrapped my two components TypeyThing and ListOfThings in a div.

Here's TypeyThing:

    TypeyThing = () =>
        <input
            type="text"
            value={store.getState().text}
            onChange={({target:{value: text}}) => 
                store.dispatch({
                    type: 'ADD_TEXT',
                    text
                })}
            onKeyPress={e => {
                if(e.key === 'Enter') 
                    store.dispatch({
                        type: 'ADD_TO_LIST'
                    })
            }}/>,

See how I can just use store? If I wasn't using Provider I'd have to pass it in as a parameter like so:

....
<TypeyThing store={store}/>  
....
TypeyThing = ({store}) =>  
....

Not only that, I'd have to pass store onto all of TypeyThing's children, and from those children to other children, etc.

That is just no good.

Anyway, because of the convenience provided by Provider I can do a similar trick with ListOfThings:

    ListOfThings = () =>
        <ul>
            {store.getState().list
                .map(thing => <li>{thing.text}</li>)}
        </ul>,

See ma? No need to endlessly pass the store around as a parameter to every single component!

BTW, here's what the completed app looks like:

store keeps track of what's in the text box as well as an array of strings to put in the ul. You add stuff to the ul by hitting enter.

Happy coding! :)

Looking for a software developer?