1

Currently, I have a 3 rows in a table. Each row has two column: file name and a button

  • file name is just a dummy link.

  • button will hide show a menu.

My requirements are following:

  • Click a button, it will toggle the menu. i.e. if prev it is close, it should be open. If prev is open, close.
  • When you are click on this button, if other menus are open, they should be close.
  • Each time, only 1 menu is open.

github link

git clone, npm install, npm start

I have the following code

import React, {useState, useEffect} from 'react';

function Menu({buttonName, menuIndex, currRowInd, setCurrRowInd}) {
  // inside menu
  const [open, setOpen] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const menuItems = {download: 'download', view: 'view', delete: 'delete'};

  useEffect(() => {
    if (open && menuIndex === currRowInd) {
      setShowMenu(true);
    } else {
      setShowMenu(false);
    }
  }, [open, currRowInd]);

  return (
    <div>
      <button
        onClick={event => {
          // it is mouse click
          if (event.pageX !== 0 && event.pageY !== 0) {
            // toggle
            setOpen(!open);
            setCurrRowInd(menuIndex);
          }
        }}
      >
        {buttonName}
      </button>
      {showMenu && (
        <ul style={{padding: '5px', margin: '10px', border: '1px solid #ccc'}}>
          {Object.keys(menuItems).map((item, itemIndex) => {
            return (
              <li
                tabIndex="0"
                key={itemIndex}
                style={{
                  listStyle: 'none',
                  padding: '5px',
                  backgroundColor: 'blue'
                }}
              >
                {item}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function TableElement() {
  const [currRowInd, setCurrRowInd] = useState('');

  const items = [
    {
      file: 'file1',
      button: 'button1'
    },
    {
      file: 'file2',
      button: 'button2'
    },
    {
      file: 'file3',
      button: 'button3'
    }
  ];
  return (
    <table style={{borderCollapse: 'collapse', border: '1px solid black'}}>
      <tbody>
        {items.map((item, index) => {
          return (
            <tr key={index}>
              <td style={{border: '1px solid black'}}>
                <a href="#">{item.file}</a>
              </td>
              <td style={{border: '1px solid black'}}>
                <Menu
                  buttonName={item.button}
                  menuIndex={index}
                  currRowInd={currRowInd}
                  setCurrRowInd={setCurrRowInd}
                />
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function App() {
  return (
    <>
      <TableElement />
    </>
  );
}

export default App;

I have a bug:

  1. Click button 1, it opens 1st menu (good)
  2. Click button 2, it opens 2nd menu and close 1st menu (good)
  3. Click button 1 again, 2nd menu close (good so far), but 1st menu is not open.

Any idea?

kenpeter
  • 7,404
  • 14
  • 64
  • 95

2 Answers2

0

You don't need all that state in the Menu component, it's just adding a lot of complexity. Your issue is solved simply by removing it, and changing some props around.

Link to working codesandbox

function Menu({buttonName, showMenu, handleClick}) {
  const menuItems = {download: 'download', view: 'view', delete: 'delete'};

  return (
    <div>
      <button
        onClick={event => {
          // it is mouse click
          if (event.pageX !== 0 && event.pageY !== 0) {
            // toggle
            handleClick();
          }
        }}
      >
        {buttonName}
      </button>
      {showMenu && (
        <ul style={{padding: '5px', margin: '10px', border: '1px solid #ccc'}}>
          {Object.keys(menuItems).map((item, itemIndex) => {
            return (
              <li
                tabIndex="0"
                key={itemIndex}
                style={{
                  listStyle: 'none',
                  padding: '5px',
                  backgroundColor: 'blue'
                }}
              >
                {item}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function TableElement() {
  // number is a better default. -1 will never match
  const [currRowInd, setCurrRowInd] = useState(-1);

  const items = [
    {
      file: 'file1',
      button: 'button1'
    },
    {
      file: 'file2',
      button: 'button2'
    },
    {
      file: 'file3',
      button: 'button3'
    }
  ];
  return (
    <table style={{borderCollapse: 'collapse', border: '1px solid black'}}>
      <tbody>
        {items.map((item, index) => {
          return (
            <tr key={index}>
              <td style={{border: '1px solid black'}}>
                <a href="#">{item.file}</a>
              </td>
              <td style={{border: '1px solid black'}}>
                <Menu
                  buttonName={item.button}
                  showMenu={index === currRowInd}
                  handleClick={() => {
                    // toggle
                    if (index !== currRowInd) setCurrRowInd(index)
                    else setCurrRowInd(-1)
                  }}
                />
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

azium
  • 20,056
  • 7
  • 57
  • 79
0

As mentioned, you can simplify much more the code. As only one menu has to be visible for each Table, visibility should be handled for TableElement component.

import React, { useState } from 'react';

const Menu = ({
  buttonName,
  menuIndex,
  opened,
  handleClickButton
}) => {

  const menuItems = {
    download: 'download',
    view: 'view',
    delete: 'delete'
  };

  return (
    <div>
      <button onClick={(e) => handleClickButton(menuIndex, e)}>
        {buttonName}
      </button>

      {opened && (
        <ul style={{padding: '5px', margin: '10px', border: '1px solid #ccc'}}>
          {Object.keys(menuItems).map((item, itemIndex) => {
            return (
              <li
                tabIndex="0"
                key={itemIndex}
                style={{
                  listStyle: 'none',
                  padding: '5px',
                  backgroundColor: 'blue'
                }}
              >
                {item}
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

const TableElement = _ => {
  const [currRowInd, setCurrRowInd] = useState(null);

  const items = [
    {
      file: 'file1',
      button: 'button1'
    },
    {
      file: 'file2',
      button: 'button2'
    },
    {
      file: 'file3',
      button: 'button3'
    }
  ];

  const handleButtonClick = (menuIndex, e) => {
    setCurrRowInd(menuIndex);
  }

  return (
    <table style={{borderCollapse: 'collapse', border: '1px solid black'}}>
      <tbody>
        {items.map((item, index) => {
          return (
            <tr key={index}>
              <td style={{border: '1px solid black'}}>
                <a href="#">{item.file}</a>
              </td>
              <td style={{border: '1px solid black'}}>
                <Menu
                  buttonName={item.button}
                  menuIndex={index}
                  opened={currRowInd === index}
                  handleClickButton={handleButtonClick}
                />
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

const App = _ => {
  return (
    <>
      <TableElement />
    </>
  );
}

export default App;
Calderón
  • 146
  • 1
  • 5