cbutler
cbutler

Reputation: 933

modelling reusable react components with state stored in redux

This is a software design / architecture question:

I want to model a component in react, who's state is stored in redux, but I want to be able to make multiple instances of that component. The best I can come up with is to encapsulate all the properties for the component in an object and then shove that object into an array, using an id field or index to get the component you are looking for but I'm not sure if this is the best approach. Is there a 'standard' or industry best practice way to go about this?

Upvotes: 2

Views: 54

Answers (1)

emiacc
emiacc

Reputation: 59

I would send the name and the data of the component instance as a payload of the action. So you could create a reducer for the reusable component and in this piece of state, you would create a key for each specific instance.

//reducer for generic component
export default (state, action) => {
  switch (action.type) {
    case "SAVE_GENERIC_COMPONENT": 
      return { ...state, [action.payload.name]: action.payload.data }
  }
}

Your store will be like this:

{
  ...
  genericComponent: {
    instance1: { ... },
    instance2: { ... },
    instanceN: { ... }
  }
  ...
}

Upvotes: 1

Related Questions