What Will I Learn?
In this tutorial, you will learn about how to make a simple popup modal with React Portal. New features in React Fiber (React v16.0). Actually, with react portal, you not only can make modal but the implementation can widen to tooltip, dropdown etc.
[DEMO]
Requirements
- node
- npm / yarn
- lastest version of
create-react-appnpm module
Difficulty
- Basic
Generating Project
First, make a react app with create-react-app.
Open your terminal and type
create-react-app modal-portal
cd modal portal
yarn start
So you should see a folder structure like this.
App root and Modal root
In your public/index.html replace your div with id root with two new div, one with id app-root and another one with modal-root.
app-root is where our app will be rendered and modal-root is where our modal will be rendered.
and then change root in src/index.js to app-root too.
Making modal
With react portal, you can summon your component to any element in the page! So, in my app, i decide to make the modal summoned in modal-root.
Make one component, Modal src/Modal.js
import React from "react";
import ReactDOM from "react-dom";
const Modal = ({ children }) => {
const modalRoot = document.getElementById("modal-root");
return ReactDOM.createPortal(children, modalRoot);
};
export default Modal;
With that code, the children in Modal component will be rendered in modal-root.
And then calling the modal in src/App.js
import Modal from './Modal'
class App extends Component {
state = {
showModal: false
};
handleShowModal = () => {
this.setState({ showModal: true });
};
handleHideModal = () => {
this.setState({ showModal: false });
};
render() {
return (
<div
className="app"
style={{
textAlign: "center"
}}
>
<p>This is rendered in #app-root
<p>click button to show modal</p>
<button onClick={this.handleShowModal}>Show modal</button>
{this.state.showModal && (
<Modal>
<div
className="modal"
style={{
boxSizing: "border-box",
position: "fixed",
width: "100%",
height: "100vh",
background: "rgba(0,0,0,0.9)",
top: 0,
left: 0,
padding: 30,
textAlign: "center",
color: "#eee"
}}
>
<p>This is modal, rendered in #modal-root
<button onClick={this.handleHideModal}>Hide modal</button>
</div>
</Modal>
)}
</div>
);
}
}
export default App;
You can see the Modal component are inside of App component that rendered inside app-root. But the result is Modal component rendered inside modal-root.
This happen because of React portal as given in src/Modal.js
Summary, When you click show modal it will summon Modal which portaled to modal-root. And when you click hide modal, the modal will dissapear.
You can try the result [HERE]
Posted on Utopian.io - Rewarding Open Source Contributors