Categories
React

react-overlays — Modal Transitions

Modals are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add a modal into our React app with the react-overlays library.

Modal Transitions

We can add transition effects when we open a react-overlays modal.

For instance, we can write:

styles.css

.fade {
  opacity: 0;
  transition: opacity 500ms linear;
}

.show {
  opacity: 1;
}

.backdrop.fade.show {
  opacity: 0.5;
}

.dialog {
  position: absolute;
  width: 400;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #e5e5e5;
  background-color: white;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
  padding: 20px;
}

App.js

import React, { useState } from "react";
import { Transition } from "react-transition-group";
import styled from "styled-components";
import Modal from "react-overlays/Modal";
import "./styles.css";
const FADE_DURATION = 500;

const AModal = styled(Modal)`
  position: fixed;
  width: 400px;
  z-index: 1040;
  top: 20px;
  left: 30px;
  border: 1px solid #e5e5e5;
  background-color: white;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
  padding: 20px;
`;

const fadeStyles = {
  entering: "show",
  entered: "show"
};

const Fade = ({ children, ...props }) => (
  <Transition {...props} timeout={FADE_DURATION}>
    {(status, innerProps) =>
      React.cloneElement(children, {
        ...innerProps,
        className: `fade ${fadeStyles[status]} ${children.props.className}`
      })
    }
  </Transition>
);

export default function App() {
  const [showModal, setShowModal] = useState(false);

return (
    <div className="flex flex-col items-center">
      <button
        type="button"
        className="btn btn-primary mr-3"
        onClick={() => setShowModal((prev) => !prev)}
      >
        Show Animated Modal
      </button>
      <AModal
        show={showModal}
        onHide={() => setShowModal(false)}
        transition={Fade}
        backdropTransition={Fade}
        renderBackdrop={(props) => (
          <div {...props} className="backdrop absolute inset-0 bg-black z-40" />
        )}
        renderDialog={(props) => (
          <div
            {...props}
            className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
          >
            <div className="dialog bg-white shadow rounded-lg pointer-events-auto">
              <h4 id="modal-label">I&apos;m fading in!</h4>
              <p>Anim pariatur</p>
              <button
                type="button"
                className="btn"
                onClick={() => setShowModal(false)}
              >
                Close
              </button>
            </div>
          </div>
        )}
      />
    </div>
  );
}

We create the modal with styled-component’s styled function.

We pass in the Modal component from the react-overlays library to create the modal with our own styles.

Also, we set the styles for fading with the fadeStyles object.

We set the fade effect to show during animation.

Then in App , we add the button to let us open the modal by calling setShowModal to true .

We render the items in the modal with the renderDialog prop.

It has a function that returns a component as the value.

Conclusion

We can add transition effects when modals are open when we use react-overlays to add our modal.

Categories
React

Add a Modal to a React App with Styled React Modal and react-overlays

Modals are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add a modal into our React app with the Styled React Modal and react-overlays libraries.

Styled React Modal

The Styled React Modal library lets us add a modal easily into our React app.

To install it, we run:

npm i styled-react-modal

Then we can use it by writing:

import React, { useState } from "react";
import Modal, { ModalProvider } from "styled-react-modal";
import { ThemeProvider } from "styled-components";

const StyledModal = Modal.styled`
  width: 20rem;
  height: 20rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
`;

function FancyModalButton() {
  const [isOpen, setIsOpen] = useState(false);

  function toggleModal(e) {
    setIsOpen(!isOpen);
  }

  return (
    <div>
      <button onClick={toggleModal}>Click me</button>
      <StyledModal
        isOpen={isOpen}
        onBackgroundClick={toggleModal}
        onEscapeKeydown={toggleModal}
      >
        <span>I am a modal!</span>
        <button onClick={toggleModal}>Close me</button>
      </StyledModal>
    </div>
  );
}

export default function App() {
  return (
    <ThemeProvider theme={{}}>
      <ModalProvider>
        <FancyModalButton />
      </ModalProvider>
    </ThemeProvider>
  );
}

We add the FancyModalButton component to add the modal trigger.

Inside the component, we add the StyledModal inside the component.

It’s created from the Modal.style tag.

We control whether StyledModal is open or close with the isOpen prop.

The onBackgroundClick prop lets us run code when the background is clicked.

And onEscapeKeydown lets us run code when the Esc key is pressed.

We just toggle the isOpen state to open or close the modal since we pass that as the value of the isOpen prop.

Then we use the styled modal by passing it inside the ThemeProvider and ModalProvider .

react-overlays

We can use the react-overlays library to add a modal to our React app.

To install it, we run:

npm install react-overlays

with NPM or:

yarn add react-overlays

with Yarn.

Then we can use it by writing:

import React, { useState } from "react";
import styled from "styled-components";
import Modal from "react-overlays/Modal";

const Backdrop = styled.div`
  position: fixed;
  z-index: 1040;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #000;
  opacity: 0.5;
`;

const AModal = styled(Modal)`
  position: fixed;
  width: 400px;
  z-index: 1040;
  top: 20px;
  left: 30px;
  border: 1px solid #e5e5e5;
  background-color: white;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
  padding: 20px;
`;

export default function App() {
  const [show, setShow] = useState(false);

  const renderBackdrop = (props) => <Backdrop {...props} />;

  return (
    <div className="modal-example">
      <button
        type="button"
        className="btn btn-primary mb-4"
        onClick={() => setShow(true)}
      >
        Open Modal
      </button>

      <AModal
        show={show}
        onHide={() => setShow(false)}
        renderBackdrop={renderBackdrop}
      >
        <div>
          <h4 id="modal-label">Text in a modal</h4>
          <p>Lorem ipsum</p>
        </div>
      </AModal>
    </div>
  );
}

We create the Backdrop component, which is a div with some styles applied.

Then we create the AModal component, which is a modal that has a fixed position.

And we also set the background color and box-shadow to add some effects to show with the modal.

In App , we have a button to open the modal by calling setShow with true .

And we have the AModal component that shows the modal if show is true .

We pass in the Backdrop component as the value of renderBackdrop to render the backdrop.

onHide is called when we hide the modal.

Conclusion

We can add modals easily into our React app with the Styled React Modal and react-overlays libraries.

Categories
React

Add a Modal to a React App with Rodal and Reactjs-popup

Modals are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add a modal into our React app with the Rodal and Reactjs-popup libraries.

Rodal

We can add the Rodal library by running:

npm i rodal --save

Then we can use it by writing:

import React, { useState } from "react";
import Rodal from "rodal";
import "rodal/lib/rodal.css";

export default function App() {
  const [visible, setVisible] = useState(false);

  return (
    <div>
      <div>
        <button onClick={() => setVisible(true)}>show</button>

        <Rodal visible={visible} onClose={() => setVisible(false)}>
          <div>Content</div>
        </Rodal>
      </div>
    </div>
  );
}

We import the Rodal library with its styles.

Then we set the visible prop to the visible state so that we can control when it’s shown.

We set visible to true to show the modal.

onClose is run when we click the close button.

In it, we call setVisible with false to close the modal.

It has many other options available as props.

width sets the wdith. height sets the hrigjt.

showMask controls whether we show a mask.

animation sets the animation type.

enterAnimation and leaveAnimation sets the animation for when the modal is shown or hidden..

duration sets the duration of the animation.

closeOnEsc lets us close the modal when we press escape.

For example, we can use some of them by writing:

import React, { useState } from "react";
import Rodal from "rodal";
import "rodal/lib/rodal.css";

export default function App() {
  const [visible, setVisible] = useState(false);

  return (
    <div>
      <div>
        <button onClick={() => setVisible(true)}>show</button>

        <Rodal
          enterAnimation="zoom"
          leaveAnimation="zoom"
          closeOnEsc
          visible={visible}
          onClose={() => setVisible(false)}
        >
          <div>Content</div>
        </Rodal>
      </div>
    </div>
  );
}

Other animation types available include:

  • fade
  • flip
  • door
  • rotate
  • slideUp
  • slideDown
  • slideLeft
  • slideRight

Reactjs-popup

The Reactjs-popup library lets us add a popup that’s attached to a trigger element.

To install it, we run:

npm i reactjs-popup

Then we can use it by writing:

import React from "react";
import Popup from "reactjs-popup";
import "reactjs-popup/dist/index.css";

export default function App() {
  return (
    <div>
      <div>
        <Popup trigger={<button> Trigger</button>} position="right center">
          <div>Popup content here !!</div>
        </Popup>
      </div>
    </div>
  );
}

We import the Popup component with the associated styles.

Then we set the trigger prop to the trigger element.

position lets us set the position of the popup with a string.

We can add whatever content we want between the tags.

We can also use it to open a modal by adding the modal prop:

import React from "react";
import Popup from "reactjs-popup";
import "reactjs-popup/dist/index.css";

export default function App() {
  return (
    <div>
      <div>
        <Popup trigger={<button> Trigger</button>} modal nested>
          {(close) => (
            <div className="modal">
              <button className="close" onClick={close}>
                &times;
              </button>
              <div className="header"> Modal Title </div>
              <div className="content">Lorem ipsum</div>
              <div className="actions">
                <Popup
                  trigger={<button className="button"> Trigger </button>}
                  position="top center"
                  nested
                >
                  <span>Lorem ipsum</span>
                </Popup>
                <button
                  className="button"
                  onClick={() => {
                    console.log("modal closed ");
                    close();
                  }}
                >
                  close modal
                </button>
              </div>
            </div>
          )}
        </Popup>
      </div>
    </div>
  );
}

The close function is available to let us close the modal.

The nested prop lets us open another modal in the modal.

Conclusion

We can add modals into our React app with the Rodal and react-popup libraries.

Categories
React

Add a Modal to a React App with react-modal and react-confirm-alert

Modals are something that we have to add often into our React app.

To make this task easier, we can use existing component libraries to add them.

In this article, we’ll look at how to add a modal into our React app with the react-modal and react-confirm-alert libraries.

Installation

We can install the library by running:

npm install --save react-modal

with NPM or:

yarn add react-modal

with Yarn.

Usage

We can use it by adding the Modal component into our React component.

To do this, we write:

import React from "react";
import Modal from "react-modal";

const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    marginRight: "-50%",
    transform: "translate(-50%, -50%)"
  }
};

Modal.setAppElement("#root");

export default function App() {
  let subtitle;

  const [modalIsOpen, setIsOpen] = React.useState(false);
  function openModal() {
    setIsOpen(true);
  }

  function afterOpenModal() {
    subtitle.style.color = "#f00";
  }

  function closeModal() {
    setIsOpen(false);
  }

  return (
    <div>
      <button onClick={openModal}>Open Modal</button>
      <Modal
        isOpen={modalIsOpen}
        onAfterOpen={afterOpenModal}
        onRequestClose={closeModal}
        style={customStyles}
        contentLabel="Example Modal"
      >
        <h2 ref={(_subtitle) => (subtitle = _subtitle)}>Hello</h2>
        <button onClick={closeModal}>close</button>
        <div>I am a modal</div>
        <form>
          <input />
          <br />
          <button>ok</button>
          <button>cancel</button>
        </form>
      </Modal>
    </div>
  );
}

We add the customStyles object to style the items.

And we add the modalIsOpen state to control when the modal opens or closes.

The isOpen prop controls whether the modal is opened or closed.

onAfterOpen takes a function that runs code after the modal is open.

onRequestClose takes a function that runs code after the modal is closed.

style takes an object with some properties to change the styles.

contentLabel is a label for the modal.

We call Modal.setAppElement(“#root”) to make the modal component attach to the element with ID root .

react-confirm-alert

The react-confirm-alert library is another library that lets us add a modal easily into our React app.

To install it, we run:

npm install react-confirm-alert --save

We can use it by writing:

import React from "react";
import { confirmAlert } from "react-confirm-alert";
import "react-confirm-alert/src/react-confirm-alert.css";

export default function App() {
  const submit = () => {
    confirmAlert({
      title: "Confirm to submit",
      message: "Are you sure to do this.",
      buttons: [
        {
          label: "Yes",
          onClick: () => alert("Click Yes")
        },
        {
          label: "No",
          onClick: () => alert("Click No")
        }
      ]
    });
  };

  return (
    <div>
      <button onClick={submit}>Confirm dialog</button>
    </div>
  );
}

We import the confirmAlert function and call it in the submit method to open the alert dialog with it.

The title property sets the dialog title.

message sets the message content.

buttons add buttons with the given labels and the event handlers for them.

We can also make it display a custom React component as the content:

import React from "react";
import { confirmAlert } from "react-confirm-alert";
import "react-confirm-alert/src/react-confirm-alert.css";

export default function App() {
  const submit = () => {
    confirmAlert({
      customUI: ({ onClose }) => {
        return (
          <div className="custom-ui">
            <h1>Are you sure?</h1>
            <p>You want to delete this file?</p>
            <button onClick={onClose}>No</button>
            <button
              onClick={() => {
                onClose();
              }}
            >
              Yes
            </button>
          </div>
        );
      }
    });
  };

  return (
    <div>
      <button onClick={submit}>Confirm dialog</button>
    </div>
  );
}

We just return a component in the customUI method.

It gets the onClose method from the parameter and call it whenever we want to close the dialog.

Conclusion

We can add modals easily into our React app with the react-modal and react-confirm-alert libraries.

Categories
React

Create Auto-Resizeable Lists and Grid with the react-virtualized Library

The react-virtualized package lets us display a virtualized list.

We can use it with the AutoSizer component to create a virtualized list that resizes the item.

In this article, we’ll look at how to create automatically resizeable lists and grids with the react-virtualized library.

Installation

To install it, we run:

npm i react-virtualized

AutoSizer

We can use the AutoSizer component to add the auto-resizable list.

For example, we can write:

import React from "react";
import { AutoSizer, List } from "react-virtualized";
import "react-virtualized/styles.css";

const list = Array(1000)
  .fill(0)
  .map((_, i) => i);

function rowRenderer({ key, index, style }) {
  return (
    <div key={key} style={style}>
      {list[index]}
    </div>
  );
}

export default function App() {
  return (
    <div style={{ height: "100vh" }}>
      <AutoSizer>
        {({ height, width }) => (
          <List
            height={height}
            rowCount={list.length}
            rowHeight={20}
            rowRenderer={rowRenderer}
            width={width}
          />
        )}
      </AutoSizer>
    </div>
  );
}

We create a list with the AutoSizer component with a render prop inside it.

We get the height and width from the parameter and then pass that into the List component’s height component to set the width and height of the list.

We set the rowHeight prop to set the row height of each entry.

rowRendered has a function which has the key , index and style properties from the parameter and we use that to render the entry.

index has the index of the entry.

key has the unique key of the row.

Now when we resize the screen, we see the list resize with the screen.

Grid

We can add a grid with react-virtualize’s Grid component.

For instance, we can write:

import React from "react";
import "react-virtualized/styles.css";
import { Grid } from "react-virtualized";

let list = [];
let inner = [];
let width = 500;
let height = 100;
let xCoord = 0;
let yCoord = 0;

for (let i = 0; i < 1000; i++) {
  do {
    xCoord = Math.floor(Math.random() * width);
    yCoord = Math.floor(Math.random() * height);
  } while ((xCoord <= 0) | (yCoord <= 0));

if (xCoord > 0 && yCoord > 0) {
    inner.push(xCoord);
    inner.push(yCoord);
    list.push(inner);
  }

inner = [];
}

function cellRenderer({ columnIndex, key, rowIndex, style }) {
  return (
    <div key={key} style={style}>
      {list[rowIndex][columnIndex]}
    </div>
  );
}
export default function App() {
  return (
    <div>
      <Grid
        cellRenderer={cellRenderer}
        columnCount={list[0].length}
        columnWidth={100}
        height={300}
        rowCount={list.length}
        rowHeight={30}
        width={300}
      />
    </div>
  );
}

We have the data in the list nested array.

The cellRenderer component lets us render the nested array into the grid.

We also set the columnCount to the length of the first nested array.

And we set the columnWidth to set the column width.

The height is the height of the grid.

rowCount has the row count.

rowHeight has the row height.

width has the grid width.

Then we see the nested list rendered on the screen.

Conclusion

We can create an auto-resizable list and grids with the react-virtualized library.