Make modal with react portal

in #utopian-io7 years ago (edited)

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-app npm 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.

image.png

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.

image.png

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.

image.png

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>
        <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</p>
              <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

image.png

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

Sort:  

Hey @damaera, your contribution was rejected by the supervisor @mcfarhat because he found out that it did not follow the Utopian rules.

Upvote this comment to help Utopian grow its power and help other Open Source contributions like this one. Do you want to chat? Join me on Discord.

Thank you for the contribution. It has been approved.

Personal Note:
This tutorial is very short. I think that you should give a few more explanations about the code, additional frameworks used and technical aspects. I accepted it mostly because you clearly made an effort with the styling and with the demo.

You can contact us on Discord.
[utopian-moderator]

Hey @flauwy, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Thank you.
Okay, next time I will make it like that.
So, what you mean is that, i must explain what is react-dom react ?

I agree better with your personal note :) which is why I reversed the decision. Check note below

Your contribution cannot be approved because it is not as informative as other contributions. See the Utopian Rules. Contributions need to be informative and descriptive in order to help readers and developers understand them.
Also you covered a very simple concept of displaying modals. Please have your tutorials cover vaster levels of functionality, and be more detail oriented.
Thank you!

You can contact us on Discord.
[utopian-moderator]

Coin Marketplace

STEEM 0.26
TRX 0.25
JST 0.040
BTC 92903.81
ETH 3331.70
USDT 1.00
SBD 3.29