Luke
Luke

Reputation: 105

Change class of Element inside Modal

I am trying to change the attribute "class" of an div-element inside a modal on a button click (the button is not in the modal), while the modal is not being shown. The element is a regular textline and the modal I am using is from the react-bootstrap framework.

I have tried doing it with:

onClickButton(){
  document.getElementById("elementID").setAttribute("class","toSomething");
}

but the element doesn't exist, since the modal is not showing. Therefore I get an exception running this code.

Am I missing something in my code or is there any other way to set the class property of that element?

Thanks in advance!

Upvotes: 1

Views: 321

Answers (1)

Tholle
Tholle

Reputation: 112787

Instead of trying to manipulate the DOM manually you could change a variable in state that you use as className for the modal. That way it doesn't matter if the modal is visible or not when you change it.

Example

ReactModal.setAppElement("#root");

class App extends React.Component {
  state = {
    modalIsOpen: false,
    color: "green"
  };

  openModal = () => {
    this.setState({ modalIsOpen: true });
  };

  closeModal = () => {
    this.setState({ modalIsOpen: false });
  };

  toggleColor = () => {
    this.setState(({ color }) => ({
      color: color === "green" ? "red" : "green"
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.openModal}>Open Modal</button>
        <ReactModal isOpen={this.state.modalIsOpen}>
          <div className={this.state.color}>Modal content</div>
          <button onClick={this.closeModal}> Close </button>
        </ReactModal>
        <button onClick={this.toggleColor}>Toggle color</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
.green {
  background-color: green;
}

.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-modal/3.8.1/react-modal.min.js"></script>

<div id="root"></div>

Upvotes: 3

Related Questions