scripter scripter - 3 months ago 12
React JSX Question

How to highlight multiple selection in react using redux?

I am trying to make multiple selection and highlight them. So suppose if I am displaying 5 buttons and if user clicks on a button it will be higlighted and if the user clicks on it again then it will become normal.

I am using redux store the state of my button. These button are getting created dynamically based on how many they are.

Redcuer

CurrentReducer(state = {court:{}}, action){
switch (action.type){
case 'COURT_SELECTED':{
return {...state,
court: action.payload
}
}}


Dispatcing action on onClick

this.props.dispatch(actions.selected({type:'COURT_S', payload: id}))


I had thought of storing id's in court by making it as an array or storing id with true or false in an object.
can anyone give me a simple working solution which is super easy

Answer

You can do something like this:

reduser

const selectedCourts = (state = {}, action) => {
  switch (action.type) {
    case 'COURT_TOGGLE': {
      return {
        ...state,
        [action.id]: !state[action.id]
      };
    }
  }
  return state;
};

action

dispatch({type: 'COURT_TOGGLE', id});

So you'll have piece of state like this:

selectedCourts: {
    1: true,
    2: false,
    3: false,
    ...
  }

I recommend you to use combineReducers to split your reducer into smaller parts so each subreducer would handle a simple part of your state like an array or one level object or boolean variable.

CurrentReducer.js

export default combineReducers({
  selectedCourts,
  ...
});