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
