aryzing aryzing - 15 days ago 6
React JSX Question

Displaying one of multiple components best practices

I'm currently using React and Redux, and I'm trying to find the best way of displaying one of multiple components. That is, I have various modals set up (

<Modal-1 />
,
<Modal-2 />
, ...,
<Modal-N />
) and a variable in my Redux store describes which modal should show.

// store
modal: {
name: 'Modal-8', // null or undefined --> no show
payload: 'some data the modal might need'
}


An initial approach to issue would be something like

export default Modals ({ name }) => (
{name === 'Modal-1' && <Modal-1>}
{name === 'Modal-2' && <Modal-2>}
{/*...*/}
{name === 'Modal-N' && <Modal-N>}
)


Is there an efficient way of selecting to render one out of many components based on a variable/flag?

Do you suggest an alternative approach to displaying different modals?

Answer

I would use a hash table for this

export const Modals = {
    'Modal-1': Modal1,
    'Modal-2': Modal2,
    'Modal-3': Modal3
}

the way you would use this is

const Component = Modals[name]; and in the render return <Component />


I would strongly you rename your components, Modal-1 is a bad naming convention and doesn't mean much to anyone. LoginModal ImageModal things like that mean a whole lot more to a developer.

Comments