AndreyM
AndreyM

Reputation: 1413

mapStateToProps and properties not coming from the stores

Is it a good idea to include properties not coming from the store in mapStateToProps?

e.g.

const fooBar = () => 'foobar!'

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
    fooBar
  }
}

Upvotes: 0

Views: 517

Answers (1)

lux
lux

Reputation: 8436

Yes, this is an acceptable use case - however, we might be able to implement this functionality a bit cleaner. For instance, mapStateToProps in react-redux accepts a second argument, titled ownProps, which are the props passed to the container component in question:

Via https://github.com/reactjs/react-redux/blob/master/docs/api.md

[mapStateToProps(state, [ownProps]): stateProps] (Function): ...If ownProps is specified as a second argument, its value will be the props passed to your component, and mapStateToProps will be re-invoked whenever the component receives new props.

So perhaps rather than instantiating fooBar inside of your container component, why not pass it as a prop to the component itself, and then access it via ownProps?

Some Other Component

 <MyContainer fooBar={() => alert('foobar!')}

MyContainer

const mapStateToProps = (state, ownProps) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
    fooBar: ownProps.fooBar
  }
}

Upvotes: 2

Related Questions