Home > front end >  Setting parent sibling as visible in reactjs
Setting parent sibling as visible in reactjs

Time:05-01

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"))

CodePudding user response:

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

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

CodePudding user response:

One way of doing it would be to include the Popup component in Container component like below.

function Container() {
    const [isVisible, setIsVisible] = useState(false);

    const setPopupVisible = () => {
    console.log('Popup should appear')
    setIsVisible(true);
  }
    return (
    <ul>
      <li onClick={setPopupVisible}>Item 1</li>
      <li onClick={setPopupVisible}>Item 2</li>
    </ul>
    <Popup visible={isVisible} />
  )
}

and the Popup component will be like below. Use useEffect to detect props change

function Popup({visible}) {
    const [visible, setVisible] = useState(false);

    useEffect(()=>{
       setVisible(visible);
    }, [visible]);

    return (
    visible ? <div>
      <h3>Popup</h3>
    </div> : ''
  )
}
  • Related