Home > Blockchain >  Importing CSS files in to React JS
Importing CSS files in to React JS

Time:12-01

I was following a tutorial to learn to react. In this tutorial, they asked me to do an information page and add some styling to this page. When I hard coded the styles inside my index.js there will be no problem but when I want to use separate Style.css I can't import it. I don't know why. All files are on the same level.

import'./Style.css';

// Children Components
function Header() {
    return (
        <div>
            <header>
                <nav className="header">
                    <div><img src="images.png" width="80px"></img></div>
                    <div><h1>RedCloud</h1></div>
                    <div ><ul className="navitems">
                        <div ><li>Home</li></div>
                        <div ><li>Profile</li></div>
                        <div ><li>Movies</li></div>
                    </ul></div>
                </nav>
            </header>
        </div>
    )
}

//parent
function Page() {

    return (
        <div>
            <Header />
        </div>
    )

}
ReactDOM.render(<Page />, document.getElementById("root"));

For ReactDOM I am using CDNs which I am calling them in HTML file instead of importing them. And this is my CSS file.

.header {
    display: "flex";
}

.navitems{
    display: "flex";
    list-style: none;
    justify-content:'space-between';
}

.navitems > div{
    padding:"10px";
    justify-content:'space-between';
}

I don't know why but it seems like I can not import Style.css. And below I added my HTML file for extra. Thank you.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="/Style.css">
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    
</head>
<body>
    <div id="root"></div>
    <script src="index.js" type="text/babel"></script>
</body>
</html>

I double checked the file name, pathing, unsaved files and correct naming of the attributes.

CodePudding user response:

Try

import styles from 'style.css';

and when you are defining the class names,

<div className={styles.header}> </div>

PS: I would suggest using SCSS instead of CSS since it has more advanced and modified features

CodePudding user response:

i used this method

import styles from './Dashboard.module.css';

then

 <div className={styles.SideBar}>  
  • Related