Style sheet is not styling React Component - reactjs

I searched for similar problems a lot but couldn't come up with a solution.
I integrated React.js with my working project. I am using Webpack.
Everything runs properly except styling.
I have Style.scss and I import this file in my react file. It compiles without an error but the actual style is not applying to the element.
The inline style works and other classes that are included normally also are fine.
Style.scss
.wtf {
font-weight: bold;
font-size: 40px;
}
Test.js
import React from 'react';
import '../Styles/Style.scss';
const style = {
border: 'solid 5px green'
};
export default class Test extends React.Component {
render() {
return (
<div style={style} className='wtf text-danger'>
Am I React.Component? And I am working too?
</div>
);
};
}
According to the snippet above, text-danger applies color red and border:solid 5px green works too, however, the style is specified in Style.scss is not working.
I checked compiled file and it seems like my scss style code exists there
This is the result in the browser
My webpack.config.js file content is below:
const path = require( 'path' );
module.exports = {
mode: 'development',
entry: {
rooms: './react-src/rooms/rooms.js',
tasks: './react-src/tasks/tasks.js'
},
output: {
filename: '[name].js',
path: path.resolve('../htdocs/react-dist')
},
module: {
rules: [
{
test: /\.scss$/,
use: [
// style-loader
{ loader: 'style-loader' },
// css-loader
{
loader: 'css-loader',
options: {
modules: true
}
},
// sass-loader
{ loader: 'sass-loader' }
]
},
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
};
Any idea what is the problem?
Solved
According to my example and my Webpack configuration, it was compiling styles so generating a new class name.
So, that huge token highlighted above is my actual class name which I have to use.
It can be imported as an Object so I can access class name as a property.
This is how it worked.
import React from 'react';
import style from '../Styles/Style.scss';
export default class Test extends React.Component {
render() {
return (
<div className={style.wtf}>
Am I React.Component? And I am working too?
</div>
);
};
}

if you modify your webpack config to:
{...
loader: 'css-loader',
options: {
modules: false
},
...}
you can use regular className property

Related

LESS style not applied to react component in react+webpack application

In a react + web pack application, I'm trying to style my react component using LESS, but the style does not get applied, although I get no errors, so I wouldn't know where to look. Of course, my devDependencies includes less, less-loader, CSS-loader and style-loader.
webpack.config.js
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
"babel-loader",
"eslint-loader"
]
},
{
test: /\.(c|le)ss$/,
use: [
"style-loader",
"css-loader",
"less-loader",
]
}
]
},
resolve: {
extensions: [".js", ".jsx"],
alias: {
"#components": path.resolve(__dirname, "src/components"),
"#containers": path.resolve(__dirname, "src/containers")
}
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './dist',
hot: true
}
};
components/App/App.jsx
import React from "react";
import Body from "#components/Body/Body.jsx";
import Footer from "#components/Footer/Footer.jsx";
import styles from "./App.less";
class App extends React.Component {
render() {
return <div className={styles.root}>
<h1> test </h1>
<Body />
<Footer />
</div>;
}
}
export default App;
components/App/App.less
.root {
width: 100%;
height: 100%;
background-color: coral;
h1 {
margin-top: 200px;
color: red;
}
}
I expected to see the style applied, but it's not.
Try setting "root" as string-value to className.
The way your webpack has been configured, the content of the LESS-files will not be exported as css-rules but only collected to be rendered into a style-tag.
You need to import the less-file, so webpack knows which files to consider, but you neither can access its rules, or its styles. So to make it work, you simply set the CSS-class names so that the compiled CSS-rules match.
I had to enable CSS Modules in the Webpack config:
{
test: /\.(c|le)ss$/,
use: [
"style-loader",
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: "[path][name]__[local]--[hash:base64:5]",
},
},
"less-loader"
]
},

How to add classnames from less with webpack and react?

I have a webpack configuration that uses less-loader, css-loader, and style-loader. When I import less file into my component file, the css is visible in chrome's devTools, but the classname is not.
I have google'd for a couple of hours and can't seem to find anything that can explain this. I know I am suppose to use this.props.className, but I am not sure how the className gets propagated. I have also tried using static strings for the className.
Here is my webpack config:
module: {
rules: [
...
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
}
]
},
Here is my component:
import React from 'react';
import {AppBar} from '#material-ui/core';
import '../styles/layout.less';
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<AppBar className='header'></AppBar>
);
}
}
export default Home;
I expect the className to be header, but it doesn't show any class names i provide. It only happens with Material-UI components.
Sorry for late answer, recently had similar problem with 'antd' library and theme modification using less files. I had to split my webpack configuration into two parties (for node_modules and for resources) as follow:
{
test: /\.less$/,
include: /node_modules/,
use: [
{
loader: 'style-loader' // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJs
},
{
loader: "less-loader", // compiles Less to CSS
options: {
javascriptEnabled: true
}
}
],
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader' // creates style nodes from JS strings
},
{
loader: 'css-loader', // translates CSS into CommonJs
options: {
modules: true
}
},
{
loader: "less-loader", // compiles Less to CSS
options: {
javascriptEnabled: true
}
}
],
}
Hope that helps.

Webpack react sass not understanding #functions

I have sample react app and using scss. I have 2 scss file:
Colour palette:
$_color-base-white: #FFF;
$_color-base-black: #000;
$_color-base-grey: #DCDCDC;
$_color-base-charcoal: #404040;
$_color-base-turquoise: #50E3C2;
$_color-base-red: #e3454f;
$_color-base-blue: #006DEF;
$_color-base-green: #009d2f;
$palettes: (
white: (
x-light: lighten($_color-base-white, 60%),
light: lighten($_color-base-white, 40%),
mid-light: lighten($_color-base-white, 10%),
base: $_color-base-white,
mid-dark: darken($_color-base-white, 10%),
dark: darken($_color-base-white, 40%),
x-dark: darken($_color-base-white, 60%)
)
);
#function palette($palette, $tone: 'base') {
#return map-get(map-get($palettes, $palette), $tone);
}
And then I have App.scss file inside React Component:
#import '../../assets/styles/colour_semantics';
.app-header {
color: $palettes(white, mid-light);
}
And App component looks like this:
import React, { Component } from 'react';
import './App.scss';
class App extends Component {
render() {
return (
<div className="app">
<h1 class="app-header">Hello World</h1>
</div>
);
}
}
export default App;
When using only defined colours like $_color-base-white in App scss everything is ok and working but when want to use $palettes:
index.js??ref--5-1!./node_modules/sass-loader/lib/loader.js??ref--5-2!./src/containers/App/App.scss:1 Uncaught Error: Module build failed:
$palettes: (
^
(white: (x-light: white,
Why can I not use functions? Webpack plugin config looks like this:
{
test: /\.(sass|scss)$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader", options: {
sourceMap: true,
importLoaders: 2
},
}, {
loader: "sass-loader" , options: {
sourceMap: true
},
}]
},
You are calling the list and not the function.
.app-header {
color: $palettes(white, mid-light);
}
Should be
.app-header {
color: palette(white, mid-light);
}

unable to use styles from local css file

I am creating reactjs web app where I am trying to use styles from a local css file. Source code is given for reference.
/src/css/aboutcompany.css
.center {
text-align: center;
color: red;
}
/src/AboutCompany.js
import React,{Component} from 'react';
import style from './css/aboutcompany.css';
class AboutCompany extends Component{
render(){
return(
<div>
<p className="style.center"> Company</p>
<hr/>
Technologies is leading Company providing end to end software solutions to customers globally. We are specialized in every vertical of industries and deliver quality solutions using latest technologies.
</div>
)
}
}
export default AboutCompany;
webpack.config.js
var config = {
entry: './src/index.js',
output: {
path:'/build/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8081,
historyApiFallback: true
},
module: {
rules: [
{
test: /\.(jpg|png|svg)$/,
use: 'url-loader'
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: 'css-loader'
}
]
}
}
module.exports = config;
As you can see in the AboutCompany.js here <p className="style.center"> Company</p> we are trying to use css class center , but it does not work. Can someone tell me where am I wrong.
To make use of css modules in development first you need to install style-loader:
$ npm install style-loader --save-dev
then in your configurations pass modules=true as an option to css-loader
{
test: /\.css$/,
use: ['style-loader', 'css-loader?modules=true']
}
finally in your jsx code you can call your classes like this:
<p className={styles.center}/>
and you are done.

React-Date "SingleDatePicker" not working as expected?

I am using react-dates and trying to implement singledatepicker. All the functionality is working but I dont know why all the default styles are gone. I am also using babel "transform-class-properties"
import React from 'react';
import moment from 'moment'
import 'react-dates/initialize';
import {SingleDatePicker} from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
const now= moment();
export default class ExpenseForm extends React.Component{
state={
description:'',
note:'',
amount:'',
createdAt:moment(),
calendarFocused:false
}
onDateChange = (createdAt)=>{
this.setState(()=>({createdAt}));
}
onFocusChange =({focused})=>{
this.setState(()=>({calendarFocused:focused}))
}
render(){
return(
<div>
<h3>ExpenseForm</h3>
<form>
<SingleDatePicker
date={this.state.createdAt}
onDateChange={this.onDateChange}
focused={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
/>
</form>
</div>
)
}
}
Here is my Webpack config file and it is loaded with css-loader
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},{
test: /\.s?css$/,
use:['style-loader','css-loader','sass-loader']
}
]
},
devtool:'cheap-module-eval-source-map',
devServer:{
contentBase:path.resolve(__dirname, 'public'),
historyApiFallback:true
}
};
I had exact the same problem when integration react-dates into my project, and I believe the root cause is that the css module in your project also compile the css of react-dates which leads to missing of the style. To solve this problem, you could modify the rule in your module like:
...your original css module rule
exclude: [
/node_modules/
]
after applying this rule, you might encounter another issue which is that these css files can't be properly handled due to being excluded, you should then add another css module to handle those css file that you don't want to mess with, for example:
exports.vendorCss = {
test: /\.(css|scss|sass)$/,
include: [/node_modules/],
loaders: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
and there you have it!! Hope this can help!

Resources