0

I need help with a code I have been struggling with for days.

I have a list of components that I generated dynamically from an array. Each of the generated components have a button to show a text when clicked. I have been able to show/hide the text when each button is clicked however I can't make the text hide when the body of the document is clicked.

import ReactDOM from "react-dom";
const items = [
  {
    id: 1,
    text: "wake"
  },
  {
    id: 2,
    text: "sleep"
  }
];
const ButtonText = ({ id, choosenItem }) => {
  const outsideClick = (e) => {};
  React.useEffect(() => {
    document.addEventListener("click", outsideClick);
  });
  return (
    <div>
      {choosenItem === id && (
        <p style={{ backgroundColor: "yellow" }}>
          Text inside {choosenItem}
        </p>
      )}
    </div>
  );
};

export default function App() {
  const [choosenItem, setChoosenItem] = React.useState(null);
  const open = (id) => {
    setChoosenItem(id);
  };
  return (
    <div>
      {items.map((item) => {
        return (
          <React.Fragment key={item.id}>
            <p>{item.text}</p>
            <button type="button" onClick={() => open(item.id)}>
              click
            </button>
            <ButtonText
              id={item.id}
              setChoosenItem={setChoosenItem}
              choosenItem={choosenItem}
            />
          </React.Fragment>
        );
      })}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

https://codesandbox.io/s/recursing-snyder-3dwo59?file=/src/App.js

Thanks in anticipation

wales
  • 1
  • does this help: https://stackoverflow.com/questions/32553158/detect-click-outside-react-component – Kritish Bhattarai Apr 23 '22 at 18:43
  • @kritiz thank you for the time and article. Unfortunately, it doesn't help – wales Apr 23 '22 at 20:03
  • what @kritiz sent a link of should work... I edited your sandbox see it works https://codesandbox.io/s/heuristic-sea-y833lf – Anuj Apr 23 '22 at 20:25
  • @anuj. Thank you for your time and effort. This is close to what I want to achieve but not exactly. I want to be able to hide the text even if I click anywhere else inside the parent wrapper asides from where the text is displayed. what you did was to hide the text when mousedown event is fired outside the parent wrapper only. – wales Apr 23 '22 at 21:37
  • Hi guys thank you for the help. I was able to come up with a hack. when one of the buttons is clicked I popup an overlay with a high z-index but lower than the shown text and transparent background. Here is the link to sandbox [link](https://codesandbox.io/s/gracious-brook-37dyei?file=/src/App.js) – wales Apr 24 '22 at 14:06

0 Answers0