Ad

React/redux + Bootstrap, Make Modal Show Unique For Component

I have a component that shows a modal to pop up some content in my map. I have a pretty straight forward set up :

The JSX looks like this :

  <Modal show={this.props.results.showPreviewModal} >
         {myPreviewContent}
  </Modal>

2 action-creators to open, close, and set the current item :

export function previewAsset(result) {
    return {
        currentResult: result,
        type: actions.PREVIEW_ASSET
    };
}

export function closePreviewModal() {
    return {
         type: actions.CLOSE_PREVIEW_MODAL
    };
}

And their reducers :

case actions.PREVIEW_ASSET:
      return state.set('currentPreview', action.currentResult).set('showPreviewModal', true);

case actions.CLOSE_PREVIEW_MODAL:
      return state.set('showPreviewModal', false);

Now, this seems to work fine. However, the issue is that the component that has the modal inside of it is inside a map, as it is a singular search result (each result component has a some functionality so it is it's own component that is mapped over with results). The issue is that if I have 10 results, this modal opens 10 times when I click the button that fires the previewAsset action.

This makes sense, because the showPreviewModal is accessible by all components, but what I am wondering is if there is a way to make then unique for each component individually, so only the 1 modal opens, not all 10. Unsure how to approach this within react/redux, would very much appreciate any advice, thanks!

Ad

Answer

An approach I've used successfully is to pull the Modal component out of the loop (or map() in this case), and have a reducer for currentItem or something similar, which gets set when an item is selected (you could also use currentItemIndex, and then select the current item based on that in your connect() call).

In the parent component, you'd have the Modal as a child, and only display it if that currentItem is not null.

Here's a quick JSBin example to show you what I mean:

http://jsbin.com/fefoxoy/edit?html,js,console,output

Ad
source: stackoverflow.com
Ad