I work on React apps on my spare time. I try to leverage the concept of HOCs and component reusing.

I have some components where I have a form, and I created a component for showing a modal, for instance to ask for user confirmation or show a message after an operation has been done. I reuse this modal on several forms. The modal component looks like this.

import React, { Component } from "react";

export default class ModalWindow extends Component {
  state = { show: this.props.show };

  hideModal = () => {
    this.setState({ show: false });

  render() {
    const { id, title, children } = this.props;
    return [
        className={`modal ${!this.state.show ? "fade" : "show-modal"}`}
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLiveLabel">
                <span aria-hidden="true">×</span>
            <div className="modal-body">

As you can see, I receive the show property from parent component. However, I would like to be able to close the modal window, but there's the dilemma. If I rely on the prop to show or hide the modal, I would need to pass a function from parent component to be triggered by the close button of the modal, and manage state of the modal on my parent component.

I can do that but I think it is too much effort and code in my parent component just to manage a simple modal component. On the other hand, I can try to manage show status of my modal inside of it (as it looks in my code sample) and just initializing with prop from parent when component is constructed, and in that way I can have the function to close it inside of it, but if that's the case, if I want to show the modal again from my parent component, prop is not being read again.

Another one would be just to rely on props, without managing state inside Modal component (a functional component) and having a function on close that alters the DOM by toggling the show CSS class, but i know that it is highly discouraged to alter DOM manually.

At the end, a lot of effort just for toggling a couple of CSS classes.

What would be the best way to achieve this? Am I making it too complex?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.