Home > other >  Open modal on a list of items with modals in React
Open modal on a list of items with modals in React

Time:09-28

I have a list of items and each item of the list have a button that opens a modal. My problem is that I think I've done something wrong because when I click to "open a modal" it do not work... I'v made it work but it was opening all modals at the same time and I could not find out how to fix it. Any help is appreciated, I really don't know what to do!

Here my sandbox with all code: enter image description here

CodePudding user response:

In the future, rather include the relevant, problematic code in the question.

The issue is that you are including the modal in each iteration and there is no parent state to control which modal is being displayed at a time.

I suggest you modify the hook and use it from a shared parent state:

import { useState } from 'react';
import { IDimension } from '../model/metric';

const useModal = () => {
  // store which has been selected
  const [selected, setSelected] = useState<IDimension>();
  const [isShowing, setIsShowing] = useState<boolean>(false);

  const open = (dimension: IDimension) => {
    setSelected(dimension);
    setIsShowing(true);
  };

  const close = () => {
    setSelected(null);
    setIsShowing(false);
  };

  return {
    isShowing,
    open,
    close,
    selected
  };
};

export default useModal;

Then move your modal outside the loop:

          <TableBody>
            {metric?.dimensions.map((dimension) => (
              <TableRow key={dimension.name}>
                <TableCell>{dimension.name}</TableCell>
                <TableCell>{dimension.value_type}</TableCell>
                <TableCell>{dimension.doc ? dimension.doc : 'No description available'}</TableCell>
                <TableCell>
                  <Button onClick={() => open(dimension)}> Instantiate </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
       {/* outside the loop */}
        <FiltersAddition dimension={selected} isModalOpen={isShowing} close={close} />

Modified Codesandbox Demo

  • Related