Actually Using mergeProps
While working with React/Redux lately, I stumbled into a little bit of a problem: I had no idea how mergeProps
worked. As an optional argument to redux’s connect
function, it’s easy to forget about its existence entirely. So, I wanted to jot down some quick notes on how to use it before I forgot them.
MergeProps
is used by redux to bundle together the mapStateToProps
and mapDispatchToProps
functions specified in your containers. If you don’t invoke mergeProps
in the connect
function, it’ll use the default mergeProps, which creates a generic object which contains propsFromState
, propsFromDispatch
, and propsFromParentComponents
. However, when you define mergeProps
yourself, you can pass it even more props.
In my use case, we wanted to bundle up two onClick
methods, so that we don’t need to specify them down in the connected component. After passing in the usual props, we defined a generic object to be merged in with them. This object had our functions defined, as shown below.
return Object.assign({}, propsFromState, propsFromDispatch, ownProps, {
closeCaseWithReset: () => propsFromDispatch.closeCaseWithReset(propsFromState.caseNumber, ownProps.logonId, propsFromState.oAuthToken),
closeCaseAndGoHome: () => propsFromDispatch.closeCaseAndGoHome(propsFromState.caseNumber, ownProps.logonId, propsFromState.oAuthToken)
});
This was part of a larger refactor, which ensured that we weren’t passing props like oAuthToken all the way down as ownProps
from component to component. Using mergeProps made our presentational components cleaner, pulling their method definitions away, so that they could just concentrate on rendering their elements correctly, not defining functions to communicate with the rest of the app.