Harshith J.V. Harshith J.V. - 3 months ago 12
Javascript Question

Access props sent to components along with Redux state data

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.

Answer

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]
  };
}
Comments