19

Normally you can access props sent by parent to child on child component. But when redux is used on child components the props sent by parent is lost with use of 'connect' method which maps redux state with components props.

E.g.:

Declaring a component with properties: <A_Component prop1='1' prop2='2' />

Accessing without redux on child component, works fine: this.props.prop1 or this.props.prop2

Same statements will give undefined error if redux states are used.

Harshith J.V.
  • 877
  • 1
  • 8
  • 21

2 Answers2

42

Own component props are available as second argument of mapStateToProps function:

// ParentComponent.js

// ... other component methods ...
render() {
  return <TodoContainer id="1" />
}

// TodoContainer.js

// `ownProps` variable contains own component props
function mapStateToProps(state, ownProps) {
  return {
    todo: state.todos[ownProps.id]
  };
}
1ven
  • 6,776
  • 1
  • 25
  • 39
9

react-redux connect method passes props to the wrapped element. The connect method can receive 3 methods:

  • mapStateToProps - create the data props
  • mapDispatchToProps - create the actions props
  • mergeProps - combine the props produced by the 2 previous methods, and adds the parent assign props (ownProps / parentProps).

Usually you only override the mapStateToProps and or mapDispatchToProps, and you use the default mergeProps (defaultMergeProps).

This is the definition of defaultMergeProps method:

const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
  ...parentProps, // ownProps
  ...stateProps, // mapStateToProps
  ...dispatchProps // mapDispatchToProps
})

So unless you override defaultMergeProps by your own mergeProps method, you'll always get the props assigned by the parent.

btw - both mapStateToProps and mapDispatchToProps receive ownProps as well, so they can combine them with the state, and create new data props / actions props.

Jay Lim
  • 371
  • 3
  • 14
Ori Drori
  • 183,571
  • 29
  • 224
  • 209