Search code examples
reactjsreduxreact-redux

What is ownProps in react-redux?


I am reading the API on react-redux and looking at one of Redux' github examples: Redux todo app

One of the containers, FilterLink, has mapDispatchToProps (and mapStateToProps) to accept two arguments, one of them being ownprops.

const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => {
    dispatch(setVisibilityFilter(ownProps.filter))
  }
})

The API docs says:

"If your mapStateToProps function is declared as taking two parameters, it will be called with the store state as the first parameter and the props passed to the connected component as the second parameter, and will also be re-invoked whenever the connected component receives new props as determined by shallow equality comparisons. (The second parameter is normally referred to as ownProps by convention.)"

I still can't fully grasp what it does. Can someone explain what ownProps does with a different example?


Solution

  • ownProps are the attributes that are passed when the component is used. In plain React these would be just called props.

    for example in Footer.js the FilterLink is used as:

    <FilterLink filter="SHOW_ALL">
      All
    </FilterLink>
    

    So mapStateToProps method would be called with ownProps having the value:

    {
      "filter": "SHOW_ALL",
      "children": ...
    }
    

    The mapStateToProps method is used in a Redux-wrapped component to combine the explicitly passed properties (ownProps) with the state handled by the Redux store into the props of the wrapped component.

    So in your linked example of FilterLink

    const mapStateToProps = (state, ownProps) => ({
      active: ownProps.filter === state.visibilityFilter
    })
    

    the component is active (this.props.active == true) if the filter attribute (e.g. SHOW_ALL) matches the visibiltyFilter in state, i.e. if it is currently filtered by this value.