Search code examples
reactjsreact-bootstrap

How do I apply custom CSS to Modal dialog - React-bootstrap


I am new to React here and I am trying to apply CSS to a Modal dialog.

I've created a css file: /css/mycss.css

/css/mycss.css

.test {
    width: 90%;
    color: red;
}

At the root level, I have my modal dialog JSX file:

MyModal.jsx

//more code above
<Modal
   {...this.props}
   show={this.state.show}
   onHide={this.hideModal}
   dialogClassName="test"
>
//more code below

As I understand it, I'm supposed to use the dialogClassName prop to apply CSS to the modal dialog. I'm trying to access the class selector in my CSS file and pass it into the prop as shown.

Do I have to import the CSS?

import test from '/css/mycss.css';

That didn't work. What do I do to get the CSS to show?

Edit:

I've tried

import styles from './css/mycss.css'; // dialogClassName='styles.test';
import { test } from './css/mycss.css'; // dialogClassName='test';
import .test from './css/mycss.css'; // dialogClassName='test';
import {.test} from './css/mycss.css'; // dialogClassName='.test';
import './css/mycss.css'; // dialogClassName='test';

None of that applies the CSS.

Edit 2:

I tried import styles from './css/mycss.css' again and then did dialogClassName = {styles.test};. That actually worked...but sort of. The text colors did change to red but the width of the Modal dialog is still pretty stagnant. It is not 90% of the screen or 10% of the screen no matter what I change the width attribute to. So first, why was the tutorial I was following telling me to pass a string to dialogClassName? And how do I get the width of the modal dialog to change?


Solution

  • You said that you are using webpack. If you don't have installed css loader.

    npm install css-loader --save-dev
    

    Now you can import your partial CSS files in React components. This example is when you have CSS files in the same direction as a js file.

    import componentStyle from './componentStyle.scss';
    

    There are more way how to import css files. This I use because you can go inside the file like this: className={componentStyle.classInside}.

    Webpack example:

    module.exports = {
       module: {
         loaders: [
           { test: /\.css$/, loader: "style-loader!css-loader" }
         ]
       }
    };
    

    Also, you can use SASS, LESS, etc. in the same way.