Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the style of a modal using react-modal

I have this object, with the styles I want for the modal:

const customStyles = {
  content: {
    top: '35%',
    left: '50%',
    right: 'auto',
    bottom: 'auto',
    marginRight: '-50%',
    width: '60%',
    transform: 'translate(-40%, -10%)',
  },
};

Then I pass that styles to the modal like this:

            <Modal
              isOpen={this.state.modalIsOpen}
              onRequestClose={this.closeModal}
              style={customStyles}
            >

And it works fine but I want to pass a class, not create a customStyle object inside the component.

I try something like this, first creating the modal class:

.modal {
  top: '35%';
  left: '50%';
  right: 'auto';
  bottom: 'auto';
  marginRight: '-50%';
  width: '60%';
  transform: 'translate(-40%, -10%)';
}

and then:

            <Modal
              isOpen={this.state.modalIsOpen}
              onRequestClose={this.closeModal}
              className="modal"
            >

But it didn't work. What am I doing wrong?

like image 649
Liz Parody Avatar asked Jan 29 '23 08:01

Liz Parody


2 Answers

It should be portalClassName:

<Modal
  isOpen={this.state.modalIsOpen}
  onRequestClose={this.closeModal}
  portalClassName="modal"
>
like image 128
SSS Avatar answered Jan 31 '23 08:01

SSS


I think there might be a billion ways to do this, here is just one that uses CSS Modules. If you put your styles into a separate .css.js file you can import it in your module:

/// modal.css.js ///
export default {
  modal: {
    top: '35%',
    left: '50%',
    right: 'auto',
    bottom: 'auto',
    marginRight: '-50%',
    width: '60%',
    transform: 'translate(-40%, -10%)'
  },
  greenText: {
    color: 'rgb(0,255,100)'
  },
  style3: {
    marginRight: '-25%'
  }
}

You can then assign your styles by accessing them as you would with any object and apply them to your component on the style attribute

import styles from './modal.css.js'

...

<Modal
  isOpen={this.state.modalIsOpen}
  onRequestClose={this.closeModal}
  style={styles.modal}
>

if you want to apply multiple styles to your component you give the style attribute an array. This would allow you to apply styles from multiple imported style objects.

<Modal
  isOpen={this.state.modalIsOpen}
  onRequestClose={this.closeModal}
  style={[styles.modal, styles.greenText]}
>
like image 29
Lucas Kellner Avatar answered Jan 31 '23 09:01

Lucas Kellner