Search code examples
javascriptreactjssetstate

Setting parent sibling as visible in reactjs


I want to make a popup window and after clicking on one of multiple items. I figured that possibly the best solution would be to have the popup element in top level of dom rather than copy it to each of the list item. Was trying to figure out a way to change it's state and would like to ask for help doing it. Also would appreciate a suggestion on how I could handle popup buttons to have seperate handlers for each list item.

const { useState } = React;

function App() {
    return (
    <div>
      <Container/>
      <Popup />
    </div>
  )
}

function Container() {
    const setPopupVisible = () => {
    console.log('Popup should appear')
  }
    return (
    <ul>
      <li onClick={setPopupVisible}>Item 1</li>
      <li onClick={setPopupVisible}>Item 2</li>
    </ul>
  )
}

function Popup() {
    const [visible, setVisible] = useState(false) 
    return (
    visible ? <div>
      <h3>Popup</h3>
    </div> : ''
  )
}

ReactDOM.render(<App />, document.querySelector("#app"))

Solution

  • You should use react portal to "move" your popup component to the other place inside the DOM.

    https://reactjs.org/docs/portals.html