Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React opening react-bootstrap modal in content component from sidebar

Tags:

reactjs

I was wondering what would be best way to open a react-bootstrap modal from sidebar that is in another nested component?

To clarify a bit I have a modal an it is rendered in the component which lists items and it is used for edit them when you click one of the items. What i would like to do is when user clicks on the button in the sidebar that it opens that modal to add a item to the list (change from edit to add).

At first i was thinking to move the modal to parent of the sidebar but the problem is i would have to pass props 4 times to get to the list, and that could be confusing to someone who will later edit this code.

Next i taught about the context and sure that could work but to make a global state just for that it loses its purpose.

I taught about using refs but i am not sure on how to implement them.

And last thing what i taught about was just render the modal as a new component inside the sidebar but it wont change much since i want to update the list once user has added the item and i would be in the same spot.

And i would like to avoid directly accessing DOM with id (if possible), because i would like to find a "react way" of doing this.

For example (just to visualize not the actual code)

<Root>
  <Component1>
    <Component2>
      <SideBar>
       <Button onClick={setShowModal(true)}> <!-- click here -->
      </SideBar>
    </Component2>
    <Component3>
     <Component4>
       <Modal show={showModal}/> <!-- open modal here -->
     </Component4>
  </Component3>
 </Component1>
</Root>

I would just like a hint on how to approach this and what would be the best way to do this.

like image 435
MePo Avatar asked May 16 '26 20:05

MePo


1 Answers

The most "React" way would be to store the state on the component that is the first common ancestor of the button and the modal. The downside to this approach, as you mentioned, is that you will have to pass this state down. I think this would still be a clean approach.

Another thing you could consider for this case is an event emitter. You have the Modal listen to an event to change its "open" state:

import EventEmitter from 'EventEmitter';

const eventEmitter = new EventEmitter();

export default function Modal() {
  const [open, setOpen] = React.useState(false);

  const handleToggleModal = () => {
    setOpen(!open); 
  }

  React.useEffect(() => {
    eventEmitter.addListener('toggle-modal', handleToggleModal)

    return () => {
      eventEmitter.removeListener('toggle-modal', handleToggleModal);
    }
  }, [])

 // ...

}

In the component that opens/closes the modal, you will then have to emit the corresponding event:

eventEmitter.emit('toggle-modal'); 
like image 84
Andrei Savin Avatar answered May 18 '26 09:05

Andrei Savin