Home > Software design >  How to close the menu of other child component by clicking on the current one in React
How to close the menu of other child component by clicking on the current one in React

Time:09-26

Its similar to what is present in Youtube, where clicking on the three dot menu of one video tile closes the already opened one and opens the menu of current clicked video tile

CodePudding user response:

You can use some npm package to listen to on-click-outside events (ex. react-onclickoutside, react-click-outside-listener) or you make your own listener to act on outside event and close the popup (you can refer to this link for more info. Detect click outside React component)

Your popup logic might be like the below code, you can modify the example from react-click-outside package's doc for your use case as follows:

import { ClickOutsideListener } from 'react-click-outside-listener';
 
const YourPopup = ({ SetShowPopup }) => {
    const handleClickOutside = () => setShowPopup(false);
 
    return (
        <ClickOutsideListener onClickOutside={ handleClickOutside }>
            <div>Just put your content inside</div>
            <div>You can put several elements, if you need</div>
            <div>ClickOutsideListener component will call listener only if none of those clicked</div>
            <div>
                <div>Of course we can nest items</div>
            </div>
        </ClickOutsideListener>
    );
}

CodePudding user response:

State is shared in react from top to bottom, you can't have the state of siblings affect one another, instead you should move the state to the parent and have them share it.

For your case you can make currentActive state in parent

const [currentActive, setCurrentActive] = usestate('');

Initially none is selected, the function setCurrentActive is passed to child

<Child isActive={currentActive === child.id} handleActive={() => setCurrentActive(child.id)} >

when an event occurs in parent that qualifies to being selected the handleActive function is called, and depending on the value of isActive the menu you are talking about can be hidden.

using react-onclickoutside as @sygmus1897 suggested seems like a better option since the change in state in this case will only affect the child, while moving the state to the parent will make the entire parent rerender, for an event that's expected to occur a lot shared state option will cause more rerender than needed.

  • Related