Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - override redux prop by parent

Saying i have a Container connected to redux via:

const mapStateToProps = ({ MyReducer }) => ({
    myProp: MyReducer.myProp
});

Is it possible to force the value of myProp by the parent (override redux)?

I've tried:

<Container myProp={"notReduxValue"}/>

But mapStateToProps overrides the provided value.

NOTE: I can't change the container, my question is if it can be done via the parent only.

(Of course this implies a bad state design but unfortunately it has come to that)

Thanks

like image 727
Daniel Avatar asked Oct 02 '17 10:10

Daniel


1 Answers

mapStateToProps accepts two arguments. So I guess you could override it by:

const mapStateToProps = ({ MyReducer }, { myProp }) => ({
  myProp: myProp || MyReducer.myProp,
})

In case you want to override myProp in an upper level, you can use connect's mergeProps to do so (as @OrB also described).

const mapStateToProps = ({ MyReducer }, { myProp }) => ({
  myProp: MyReducer.myProp,
})

const mapDispatchToProps = () => ({ ... })

const mergeProps = (stateProps, dispatchProps, ownProps) => ({
  ... // make your changes here
})

const ConnectedContainer = connect(
  mapStateToProps,
  mapDispatchToProps,
  mergeProps
)(Container)
like image 106
mersocarlin Avatar answered Oct 23 '22 18:10

mersocarlin