Vanilla modals and tooltips in React without libraries

Mindaugas Nakrosis
2 min readJan 13, 2021

--

Photo by Ferenc Almasi on Unsplash

Today modal and tooltip implementation can be done with many libraries not requiring for a developer to know how it works behind the scenes. However, I suggest to learn how the correct implementation should look without any dependencies.

Modals or tooltips need to always be above other elements. That can be solved with a z-index css property, however, this is more of a ‘hack’ rather than a solution itself.

The way most libraries solve this is that the element including the popup should be directly in the body html. This is one way how you can do it.
Let’s say this is our App component where we want to have a modal. You can notice that Modal component isn’t directly in the body it is in the App div. However, there is one catch, keep on reading.

class App extends React.Component {
render() {
return (
<div>
<h1>My app</h1>
<Modal open={this.state.open} onClose={this.onClose} content="Some content" />
</div>
);
}
}

This is our Modal component:

let node = null;class Modal extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
static getDerivedStateFromProps(next, prev) {
//render since we are outside of our React tree
node && ReactDOM.render(<ModalBox {...next} />, node);
return next;
}
componentDidMount() {
node = document.createElement('div');
document.body.appendChild(node);
ReactDOM.render(<ModalBox {...this.props} />, node);
}

// Used for cleanup on unMount of component
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(node);
node.parentNode && node.parentNode.removeChild(node);
}
//Returning a script is used in react-modal library
render() {
return <script />; //returns a placeholder that ignores css styles
}
}

You can see that in componentDidMount we create a div and append it to body in html. We append ModalBox component but what is it?

const ModalBox = ({ content, onClose, open }) => {
const className = open ? 'click-catcher--open' : 'click-catcher';
return (
<div className={className} onClick={onClose}>
<div className="modal">{content}</div>
</div>
);
};

In our ModalBox we add specific css classes. But what do they do?

.click-catch, .click-catcher--open {
position: fixed;
display: none;
justify-content: center;
align-items: center;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
}
.click-catcher--open {
display: flex;
}

So what click-catcher does it is an invisible element that catches all the clicks user does, so the popup closes whenever user clicks outside of the popup. When the modal closes the click catcher disappears with the help of css.

--

--

No responses yet