em_code
em_code

Reputation: 438

How to add transition on closing Modal in React and how to close when clicked outside of the Modal?

I know there are plenty of sort of questions.I've checked them but still couldn't find my way of doing it. Had to ask this as I was stuck and couldn't move anywhere. I'm new learner and still beginner in React and trying to implement Modals in my project. Here comes two questions.

  1. How can I add transition on closing?

As soon as user clicks the cards I show the modal with transition but when user closes I can't apply transition for some reason.

I change the method on either modal is open or close and do transition in css with following code:

.show .modal-parent {
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)} 
    to {-webkit-transform:scale(1)}
  }

  @keyframes zoom {
    from {transform:scale(0)} 
    to {transform:scale(1)}
  }   

Whenever user clicks the cards I show .show class and apply transition on .modal-parent where all of my modal content lies. Now I would like to do same thing when user closes the modal.

  1. How would I close the modal when clicked outside?

App.js file is here:

import React from "react";
import "./App.css";
import Cards from "./components/Cards/cards.js";
import users from "./employees.json";
import Navbar from "./components/Navbar";
import Modals from "./components/Modals";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      open: false,
    };
    this.nextPerson = this.nextPerson.bind(this);
  }

  userIndex = (cardIndex) => {
    this.setState({
      index: cardIndex,
      open: true,
    });
  };

  nextPerson = () => {
    this.setState({
      index: this.state.index + 1,
    });
  };
  previousPerson = () => {
    this.setState({
      index: this.state.index - 1,
    });
  };
  close = () => {
      this.setState({
        open: false,
      });

  };
  render() {
    let person = users[this.state.index];

    return (
      <div className="container">
        <Navbar />
        <div className="team-text"><p> Our team of <span className="team-number">42</span> strategists, designers, engineers, developers and managers<br/>make custom products for startups and leading companies. </p> </div>
        <div className="top-card">
          {users.map((user) => {
            return (
              <Cards
                user={user}
                users={users}
                key={user.id}
                userIndex={this.userIndex}
              />
            );
          })}
          <Modals
            open={this.state.open}
            users={users}
          >
            <div class="modal-parent">
              <div className={`modal-nav ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>
                <div className="modal-close">
                  <a
                    href="#close"
                    title="Close"
                    className="close"
                    type="button"
                    onClick={this.close}
                  >
                    Close
                  </a>
                </div>{" "}
              </div>

              <div className="modal-image">
                <img src={person.avatar} alt="" class="modal-avatar"></img>{" "}
              </div>
              <div> </div>
              <div className="modal-info">
                <h1 className="modal-name">
                  {person.firstName} {person.lastName}
                </h1>
                <h5 className="modal-title">{person.jobTitle}</h5>
                <h5 className="modal-department">{person.department}</h5>
              </div>
              <div className="modal-bio">
                <p>{person.bio}</p>
              </div>
              <div className="modal-contacts">
                <a href={`mailto: ${person.contact.phone}`}>
                  <span className={`material-icons phone ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>call</span><span className="contact-text">{person.contact.phone}</span>
                </a>{" "}
                <a href={`mailto: ${person.contact.email}`}>
                  <span className={`material-icons email ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>email</span><span className="contact-text">{person.contact.email}</span>
                </a>{" "}
                <a href={person.contact.url}>
                  <span className={`material-icons computer ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>computer</span><span className="contact-text">{person.contact.url}</span>
                </a>{" "}
              </div>
              <div className="modal-previous-btn">
                <button
                  className="previous-button"
                  onClick={this.previousPerson}
                  disabled={this.state.index <= 0 ? true : false}
                >Previous
                </button>
              </div>
              <div className={`modal-next-btn ${person.department === "Engineering" ? "engineer" : ""} ${person.department === "Business" ? "business" : ""}${person.department === "Design" ? "design" : ""}`}>
                <button
                  className="next-button"
                  onClick={this.nextPerson}
                  disabled={this.state.index >= 41 ? true : false}
                >Next
                </button>
              </div>
            </div>
          </Modals>
        </div>
      </div>
    );
  }
}

export default App;


Upvotes: 0

Views: 1452

Answers (1)

HermitCrab
HermitCrab

Reputation: 3274

To close a Modal when you click outside, you have to modify your Modals component. First you create a ref at the beginning:

modalRef = React.createRef();

Then you use that ref in the render function:

return (
  <div ref={this.modalRef}...

You listen to mousedown events during the lifetime of your modal component:

componentDidMount() {
    document.addEventListener("mousedown", this.handleMouseDown);
}

componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleMouseDown);
}

And you test if the click was outside of the ref in the handler:

// Mouse click event, if outside of the popup then close it
handleMouseDown= (event) => {
    if (!this.modalRef.current.contains(event.target)) {
      // Notify the parent with a callback to hide the modal
    };
}

Upvotes: 1

Related Questions