Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my CSS not applying to my React components?

Say I'm creating a React app and have some CSS for components. I've added the style-loader and css-loader to my webpack config here:

module.exports = {
  mode: 'development',
  entry: './client/index.js',
  module: {
    rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: {
          loader: 'babel-loader',
          options: { 
            presets: ['@babel/preset-react']
          }
      }
    }, {
      test: /\.css$/,
      loader: 'style-loader'
    }, {
      test: /\.css$/,
      loader: 'css-loader',
      query: {
        modules: true,
        localIdentName: '[name]__[local]___[hash:base64:5]'
      }
    }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  output: {
    path: __dirname + '/dist',
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './dist'
  },
  devtool:"#eval-source-map"
};

I have a simple CSS file just to test on one component:

.list-group-item {
    border: 1px solid black;
    outline-style: solid;
    outline-color: red;
    outline-width: medium;
}

In my app I'm applying the classname to a element in my component and importing my CSS

import React, { Component } from 'react'
import { connect } from 'react-redux'
import selectContact from '../actions/action_select_contact'
import { bindActionCreators } from 'redux'
import '../styles.css';

class ContactList extends Component {
  renderList() {
    return this.props.contacts.map((contact) => {
      return (
        <li
          key={contact.phone}
          onClick={() => this.props.selectContact(contact)}
          className='list-group-item'>{contact.firstName} {contact.lastName}</li>
      );
    });
  }
  render() {
    return (
      <ul className = 'list-group col-sm-4'>
        {this.renderList()}
      </ul>
    );
  }
}

function mapStateToProps(state) {
  return {
    contacts: state.contacts
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ selectContact: selectContact }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ContactList)

I'm also importing the CSS file in the same way in the ContactList component itself. The rest of the project is here. I would have expected to see an outline around my comtactsList but there is not. There is no CSS when I inspect the page. Why is this not getting applied?

like image 244
intA Avatar asked Apr 17 '19 13:04

intA


People also ask

Why is my CSS not being applied React?

This error is generated because the compiler is only able to import files from the src folder. Here, the CSS file is saved outside the src folder, so the compiler failed to import it. To make this code work, you just have to save the CSS file inside the src folder.

Does CSS work with React?

What is great about CSS modules is that they can be used with either normal CSS or SASS. Plus, if you are using Create React App you can start using CSS modules with no setup at all.


3 Answers

In a react project created with create-react-app or npx create-react-app, I also had the same issue.

I had imported index.css file in my App Component but my styles were not being applied properly to my React Components.

I even tried directly adding index.css file in my html file in the public folder and using link tag to link to my index.css file (which resides within src folder).

<link rel="stylesheet" href="./../src/index.css">

That also didn't work.

Finally, I read an article about 7 ways to apply CSS into React. One best way was to install node-sass into our project and use index.scss ( import './index.scss') into App Component instead of index.css.

And Hurray!!! My CSS worked fine, All the Media Queries started to work fine.

Below is the code snippet you can try.

import React from "react";
import ReactDom from "react-dom";
import './index.scss';


// --- Data to work with ---
const books = [
  {
    id: 1,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 2,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 3,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
  {
    id: 4,
    name: 'The Rudest Book Ever',
    author: 'Shwetabh Gangwar',
    img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
  },
];


const Book = ({ book }) => {
  return (
    <div className={"book"}>

      <img src={book.img} alt="book image" />

      <h3>{book.name}</h3>
      <p>{book.author}</p>
    </div>
  )
};

const Books = () => {
  return (
    <main className={"books"}>
      {
        books.map(book => {
          return (<Book book={book} key={book.id} />)
        })
      }
    </main>
  )
};


// Work a bit fast | one step at a time
const App = () => {
  return (
    <main>
      <h2>Books</h2>
      <Books />
    </main>
  )
}

ReactDom.render(<App />, document.getElementById("root"));
/* --- Mobile First Design --- */
.books{
  text-align: center;
};

.book{
  border: 1px solid #ccc;
  text-align: center;
  width: 200px;
  padding: 1rem;
  background: #001a6e; 
  color: #fff;
  margin:auto;
};

h2{
  text-align: center;
}

/* --- Adding Media Queries --- */
@media only screen and (min-width: 900px){
  .books,.persons{
    display:grid;
    grid-template-columns: 1fr 1fr;
  }
}

To install node-sass, simple do npm install node-sass --save Then rename all your .css files with .scss and your project with work properly.

The package.json should have the node-sass dependency added as shown below:

 "dependencies": {
    "node-sass": "^4.14.1",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-scripts": "2.1.5"
  },

Hope this will help many developers :)

like image 115
Imran Rafiq Rather Avatar answered Oct 07 '22 03:10

Imran Rafiq Rather


It would be helpful to see your React component as well.

Given this code, you are passing className as a property into the component rather than assigning a class to it:

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
  }

  render() {
    return (
      <div>
        /** This line specifically **/
        <ContactList className="contactList" />
        <ContactDetail />
        <AddContactModal />
      </div>
    );
  }
}

Inside your component, you would need to use className={this.props.className} on a regular HTML tag inside of your component in order to pass the className through.

like image 36
Tyler Sells Avatar answered Oct 07 '22 02:10

Tyler Sells


You can add your specific css file to index.js directly. (like this import './master.css' )

like image 2
P H Avatar answered Oct 07 '22 03:10

P H