Passing a Redux-Form action creator from container to component via React context

Rachel Cantor
Pico
Published in
2 min readNov 2, 2017

Update: I ended up deciding to just use the good ol’ props way, because after a while, context can add a bit of cruft when you have a larger app. It’s probably best to only use context if you absolutely have to. Check out this follow up post to see how I did it the props way rather than the context way.

I recently hit a wall when it came to Redux-Form being opinionated about what our data model should look like for our multi-select checkbox inputs.

Redux-Form wanted to store the info as an object with separate keys with boolean values for each checkbox, while our API only has one field expecting an array of the checkboxes that are true.

What our API wants:

[‘United States’]

What Redux-Form wants:

{  
'United States':true,
'Canada':false,
'Mexico':false
}

After making a few different attempts (including parse, FieldArray, etc.), I kept running into some unhelpful errors, so I eventually abandoned those in favor of something I came across in a Github issue — using the action creators listed in Redux-Form’s docs. I had my eye on one specifically:

change(form:String, field:String, value:any)
Saves the value to the field

The Github issue was the only example I could find where these action creators are dispatched the correct way, but it doesn’t necessarily show how to pass an action to a child component unless it’s in the same file.

Stephen Kao, my good friend and former Hillary Clinton tech team comrade, reminded me of the lesser-used/often-abused side of PropTypes: context. He showed me how to use it to manually control what value gets dispatched to the Redux store anywhere within the component tree.

Context is a way to pass things down through the tree without having to pass props down through each level. This is useful if you want to dispatch an action at any given place in a component tree. If you set it on the context of a container, any descendent component that is included from the container can invoke the action if it wants to. Just give the child component contextTypes so the component knows how to resolve the function via the context.

Here’s a simplified version of the resulting code:

Let me know if you have a different idea for handling a similar use case.

Hope this helps someone else out. 🎉

Rachel

--

--

Rachel Cantor
Pico
Writer for

Fun-loving senior full stack engineer who will post things no matter how seemingly random they are.