How should I pass a large amount of Redux actions from a container to presentational component?

98 Views Asked by At

I have the following container component which is connected to the Redux store. I wish to pass six actions to the LayerList presentational component.

LayerListContainer.jsx

import React from 'react';
import { connect } from 'react-redux'
import LayerList from '../components/LayerList'

// import actions 
import * as LayerActions from '../actions/index'

export const LayerListContainer = ({ layers }) => (
    <div>
     <LayerList layers={layers} /* I want to pass actions to this component/>
    </div>
)

const mapStateToProps = state => ({
  layers: state.layers
})

// Use default export for the connected component (for app)
export default connect(mapStateToProps, LayerActions)(LayerListContainer)

Here are the actions I wish to pass:

actions/index.js

export const addLayer = (name) => ({
    type: ADD_LAYER,
    id: nextLayerId++,
    name,
})

export const removeLayer = (id) => ({
    type: REMOVE_LAYER,
    id
})

export const toggleDragLayer = (id) => ({
    type: TOGGLE_DRAG_LAYER,
    id
})

export const moveLayerIndex = (id, destinationIndex) => ({
    type: MOVE_LAYER_INDEX,
    id,
    destinationIndex
})

export const updateLayerColour = (id, colour) => ({
    type: UPDATE_LAYER_COLOUR,
    id,
    colour
})

export const toggleLayerVisibility = (id) => ({
    type: TOGGLE_LAYER_VISIBILITY,
    id
})

Perhaps you don't consider this to be a large amount of actions. If not I would still be interested to know what best practices are for future reference on passing many actions from a container component.

1

There are 1 best solutions below

6
On BEST ANSWER

You can pass every properties of your container to your presentational using the ... spread operator syntax like this

export const LayerListContainer = props => (
  <div>
    <LayerList {...props} />
  </div>
);

Or if you just want to pass actions, you have to use bindActionCreators

import { bindActionCreators } from 'redux'

// ...

export const LayerListContainer = ({ layers, actions }) => (
  <div>
    <LayerList layers={layers} actions={actions} />
  </div>
);

// ..

const mapDispatchToProps = dispatch => ({ 
  actions: bindActionCreators(LayerActions, dispatch)
})

export default connect(mapStateToProps, mapDispatchToProps)(LayerListContainer)