Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass param to mapStateToProps in `connect()`

How do I pass in a parameter to mapStateToProps()?

EG:

const mapStateToProps = (state, dimenType: string) => {

  var jsonVariable = {}
  for(var i=1; i <= 3; i++) {
    jsonVariable[dimenType + i] = dimenType + i
  }
  console.log(jsonVariable)
  return {
    width1: state.get('width').get('width1').toString(),
    width2: state.get('width').get('width2').toString(),
    width3: state.get('width').get('width3').toString()
  }
}

This is the bit I'm unsure of:

Width = connect(
  mapStateToProps(/*redux store goes here somehow*/, 'thickness'),
  mapDispatchToProps
)(Width)

I want the redux store to still be passed into mapStateToProps but also pass "thickness". How do I do that in the connect() function?

like image 764
user2602079 Avatar asked Mar 22 '17 05:03

user2602079


1 Answers

Second parameter of connect is ownProps which are the props passed to Component. So in your case you can use it like this:

const mapStateToProps = (state, ownProps) => {
  let jsonVariable = {}
  for(var i=1; i <= 3; i++) {
    jsonVariable[dimenType + i] = ownProps.dimenType + i
  }
  console.log(jsonVariable)
  return {
    width1: state.get('width').get('width1').toString(),
    width2: state.get('width').get('width2').toString(),
    width3: state.get('width').get('width3').toString()
  }
}

I am assuming you are creating your Component like this: <Width thickness={10}/>

like image 137
cubbuk Avatar answered Nov 15 '22 05:11

cubbuk