I want to style components in react JS. I tried several ways to do that. When I try to create a CSS object and apply it to the component in the same JS file, then it is working. But when I try to apply CSS from external CSS file and import it in the JS file then it is not working. And I have also tried to save that file as filename.module.css. But it didn't help me.
The list of installed node modules and their versions is given below.
> #material-ui/core#4.9.11
> #material-ui/icons#4.9.1
> firebase#7.14.1
> react#16.13.1
> react-dom#16.13.1
> react-router-dom#5.1.2
> react-scripts#3.4.1
In webpack.config.js file of react-script module, I found below code:
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
So I guess my react project is supporting CSS files as well as SCSS and SASS files. Did I understand correctly?
header.module.css file:
.heading {
color: '#3592EF';
font-weight: '600';
letter-spacing: '2px';
}
.navButton {
color: '#444';
font-size: '16px';
padding: '4px 8px';
margin: 'auto';
margin-right: '15px';
}
Header.js file:
import React from 'react';
import { Button } from '#material-ui/core';
import styles from './header.module.css';
export default class Header extends React.Component {
render() {
return (
<div>
<span className={styles.headling}>Heading element</span>
<Button className={styles.navButton}>Home</Button>
<Button className={styles.navButton}>About</Button>
</div>
);
}
}
The output is coming with the Heading element and Home, About button. But without CSS style.
How can I solve this issue?
Thank you.
CSS module is included in react
all you have to do is building a file with the correct name like "example.module.css" and import it with the correct path if it's in the same folder `import tst from 'example.module.css' or whatever path it is in, you can replace "tst" with any any name you like.
and then you can use it in className like
<button className={tst.buttonPrimary}>Submit /button>
this video can help you more:
https://www.youtube.com/watch?v=Udf951dyTdU
Generally custom components do not accept className prop if it is not propagated to the inner of the component.
Looking in the material ui react components Button documentation, this component cannot have className property.
https://material-ui.com/components/buttons/
It means, you cannot use it. To convince your self, try to use general html <button> and it will work, you see.
Edit: grammar
first : open your terminal and run "npm install css-loader style-loader --save-dev"
These loaders enable Webpack to bundle CSS files
Second: in your webpack.config.js file, add the new loaders for interpreting CSS files:
module.exports = {
...
module: {
rules: [
...
*///
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
*////
],
},
...
};
Related
Trying to import a jpeg image to use as my background in React, but keep getting error msg
Error: Can't resolve '/img/dots.jpeg' in 'D:\Developer\mysite\src'
My App.css
.App {
text-align: center;
background-image: url('/img/dots.jpeg');
}
My App.js
import './App.css';
function App() {
return (
<div className="App" >
<h1>asdasdasd</h1>
</div>
);
}
export default App;
My project structure:
My understanding is as long as the image is in the src folder I can access it relatively through URL(). Can someone tell me what I am doing wrong?
/img/dots.jpeg is indicating that it's in the root of your project, whereas ./img/dots.jpeg will indicate that the img directory is in the same directory as the App.css file.
You can use module-resolver plugin and update your babel config with
{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"test": "./test",
"underscore": "lodash"
}
}]
]
}
#same configuration available in the link. Then you can refer your image with complete path
it seems there is wrong in importing the file in your css,
you are not telling the exact position to look for the file
.App {
text-align: center;
background-image: url('/img/dots.jpeg');
}
add these above lines it will solve the problem
I am a junior developer who just started working in a company.
I have a bit of experience in React and could not solve the current situation.
The situation i am having a trouble with is that when I import from the library that I have distributed in npm, my React project cannot recognize the styled components.
I get this error on my project.
enter image description here
I have researched and realized that the babel needs more options such as using
"babel-plugin-styled-components" option.
Unfortunately, this did not work after using the command and distributed with the commands
yarn build == webpack --mode production
Is there anyway that I can use styled-components library??
thank you!
P:S: I think I need to put more information.
Many people thankfully answered my question but I tried them and I got an another error.
enter image description here
P.S:
My file structure:
enter image description here
My code of Button
export const StyledButton = styled.button`
background-color: white;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0.5em 1em;
padding: 0.25em 1em;
${props => props.primary && css`
background: palevioletred;
color: white;
`}
`;
export default class Button extends React.Component {
constructor(props) {
super(props);
console.log("Props:", props);
}
render() {
return (
<div>
<StyledButton>{this.props.children}</StyledButton>
{/* <button> {this.props.children} </button> */}
</div>);
}
}
My index.js of Button
import Button from "./Button";
export default Button;
My index.js of src folder
export * from "./components";
My babel.config.js
module.exports = function BabelConfigJS(api) {
api.cache(true);
const presets = ["#babel/preset-env", "#babel/preset-react"];
const plugins = [
"styled-components",
[
"#babel/plugin-transform-runtime",
{
corejs: 2,
helpers: true,
regenerator: true,
useESModules: false,
},
],
[
"#babel/plugin-proposal-class-properties",
{
loose: true,
},
],
];
return {
sourceType: "unambiguous",
presets,
plugins,
};
};
PS: Error code
enter image description here
enter image description here
enter image description here
The error (which really is just an Eslint complaint) does not refer to using styled-components at all!
It's just saying components should be in PascalCase, not camelCase as you have now.
That is, instead of <styledComponent />, it'd be <StyledComponent />.
You just need to change the component name to be Uppercased, it has nothing to do with babel, etc.
// not <styledButton/>
<StyledButton/>
It is a requirement from React as in JSX lower-case tag names are considered to be HTML tags.
I am wondering how to set up an inline svg with webpack?
I am following the react-webpack-cookbook.
I have my webpack.config set up correctly with the file loader.
However the example shows using a background image like this:
.icon {
background-image: url(./logo.svg);
}
which works fine, but I want to have an inline svg image how do I do this to include my logo.svg inline in my react component?
import React, { Component } from 'react'
class Header extends Component {
render() {
return (
<div className='header'>
<img src={'./logo.svg'} />
</div>
);
}
};
export default Header
Actually Michelle's answer pointed me in the right direction, and that works nicely for loading an svg file with webpack and using it as your <img> src
However to actually get the inline svg, I needed to do the following:
Instead of file-loader use svg-inline-loader as your svg loader:
{ test: /\.svg$/, loader: 'svg-inline-loader' }
Then to load the svg inline in a component:
import React, { Component } from 'react'
import logo from "./logo.svg";
class Header extends Component {
render() {
return (
<div className='header'>
<span dangerouslySetInnerHTML={{__html: logo}} />
</div>
);
}
};
export default Header
It looks like there is an inline svg wrapper for react svg-inline-react which would be another option instead of the <div dangerouslySetInnerHTML={{__html: mySvg}} />
Here is a simple non-react solution.
Install Svg inline loader
In webpack.config.js add { test: /\.svg$/, loader: 'svg-inline-loader' }
In your js file import svg image and add it to a DOM element like so
import Svg from './svg.svg';
function component() {
const element = document.createElement('div');
element.innerHTML = Svg;
return element;
}
document.body.appendChild(component());
I hope my late answer will still be useful for someone, because I don't like any of abovementioned options.
The react-svg-loader webpack loader allows you to import SVG icons like JSX components:
import Logo from './logo.svg';
class App extends Component {
render() {
return (
<div className="App">
<Logo fill="red" className="logo" width={50} height={50} />
</div>
);
}
}
and minimum config looks like this:
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
The best part is that it just outputs the svg file contents, without any extra wrappers and dangerouslySetInnerHTML in your code.
Old question, but I didn't see this solution anywhere so I decided to post it, hoping it will help someone.
If you want to be able to style those SVG icons, you might want to load them with the raw loader:
webpack.config.js:
{
test: /\.svg$/,
loader: 'raw-loader'
}
The import in my view:
import closeIcon from 'svg/ic_close_black_24px.svg';
The template (Mustache uses 3 brackets to insert the SVG data (URL)unencoded):
<button id="closeModal">
{{{closeIcon}}}
</button>
this way the SVG data will be inserted instead of the brackets and look like this:
<button id="closeModal">
<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
</button>
I'm using Backbone with Mustache template engine with Webpack 2.5.1
If I'm not mistaken, since you're using the file loader, you can utilize it in much the same way as any other require. Webpack will turn require("./logo.svg") into a path to a file, which it will emit when it bundles.
import React, { Component } from 'react'
import mySvg from './logo.svg'
class Header extends Component {
render() {
return (
<div className='header'>
<img src={mySvg} />
</div>
);
}
};
export default Header
Similar to another answer using React, there is also a handy Vue plugin as well.
vue-svg-loader just throw it in your configuration and start using. The nice thing is it will also run your svg through SVGO to optimize it.
Configuration
{
test: /\.svg$/,
loader: 'vue-svg-loader', // `vue-svg` for webpack 1.x
options: {
// optional [svgo](https://github.com/svg/svgo) options
svgo: {
plugins: [
{removeDoctype: true},
{removeComments: true}
]
}
}
}
Usage
<template>
<nav id="menu">
<a href="...">
<SomeIcon class="icon" />
Some page
</a>
</nav>
</template>
<script>
import SomeIcon from './assets/some-icon.svg';
export default {
name: 'menu',
components: {
SomeIcon,
},
};
</script>
Angular Solution (2019): Use svg-sprite-loader to combine SVGs into a single sprite that's lazy-loaded with your Webpack bundles.
Webpack
{
test: /\.svg$/,
use: [
'svg-sprite-loader',
'svgo-loader' // Optimize SVGs (optional)
]
}
HTML
<svg>
<use xlink:href="#arrow"/>
</svg>
Angular Component
export * from 'assets/images/icons/arrow.svg';
I use export (instead of import) to prevent the AOT compiler from removing the import during tree-shaking, while allowing for minimal code in the component, but you can use import if you prefer.
To use export in this way, you must configure the compiler to expect side effects from SVG files in package.json (i.e. you can not use "sideEffects": false). See the Webpack Tree Shaking Guide
"sideEffects": [
"*.svg",
],
#svgr/webpack (npm) is the inline svg loader that create-react-app uses.
Add the rule to your webpack config:
{
test: /\.svg$/,
use: ['#svgr/webpack'],
}
Then you can import svgs as React components:
import Star from './star.svg'
const App = () => (
<div>
<Star />
</div>
)
Folks who use svg-inline-loader and who stuck with "Cannot find module" error try to install babel-plugin-inline-react-svg and add it to the babel plugins:
"plugins": [
...
["inline-react-svg", {}]
],
...
In my React project, I am using this gem for creating a dashboard: https://github.com/luqin/react-icheck
I copy pasted their first example in my code.
On the Github page, it says I should have import the css like this:
import 'icheck/skins/all.css'; // or single skin css
If I do that, I get the error:
ERROR in ./~/icheck/skins/all.css
Module parse failed: node_modules/icheck/skins/all.css Line 3: Unexpected token ILLEGAL
You may need an appropriate loader to handle this file type.
| /* iCheck plugin skins
| ----------------------------------- */
| #import url("minimal/_all.css");
| /*
| #import url("minimal/minimal.css");
If instead I do the import like this:
import 'icheck';
There is no more error, but the page doesn't have any checkbox.
So how can I do this import properly?
I also tried using style-loader so my code looks like this:
import React from 'react';
import {Checkbox, Radio} from 'react-icheck';
import 'icheck';
require("style!raw!icheck/skins/all.css");
var Criteria = React.createClass({
getInitialState: function() {
return {showGallery: false, showOtherCriteria: false};
},
toggleShowGallery: function() {
this.setState({showGallery: !this.state.showGallery});
},
toggleShowOtherCriteria: function() {
this.setState({showOtherCriteria: !this.state.showOtherCriteria});
},
render: function() {
return (
<div>
<div onClick={this.toggleShowOtherCriteria} className="btn-group" role="group" aria-label="...">
<button type="button" className="btn btn-default">Cold</button>
</div>
{style.use()}
{this.state.showOtherCriteria
?
<div onClick={this.toggleShowGallery} id="channels" className="span12">
<Checkbox
checkboxClass="icheckbox_square-blue"
increaseArea="20%"
label="Checkbox"
/>
<Checkbox
id="checkbox1"
checkboxClass="icheckbox_square-blue"
increaseArea="20%"
/>
<label for="checkbox1">First name</label>
<Radio
name="aa"
radioClass="iradio_square-blue"
increaseArea="20%"
label="Radio"
/>
</div>
:
null
}
{style.unuse()}
</div>
);
}
});
module.exports = Criteria;
However, now I get:
Module not found: Error: Cannot resolve module 'raw'
How could I use style-loader properly?
In your webpack config loader section add
module: {
loaders: [
{
test : /\.scss$/,
include : path.join(__dirname, 'sass'),
loaders : ["style", "css?sourceMap", "sass?sourceMap"]
}
]
}
By adding this code you have added three loaders namely (style,css and sass).
These three loaders perform following operations
Turn your scss files into plain CSS with the sass loader
Resolve all the imports and url(...)s in the CSS with the help of CSS loader
Insert those styles into the page with the style loader
Then require your css file from the entry point of your app e.g app.js
require('app.scss');
Edit: If you are not using sass then you don't need sass loader, also you need to change test:/\.css$/
Add webpack to your devDependencies in package.json using npm i css-loader style-loader. After that add the css-loader and style-loader to your list of loaders in webpack.config.js. Sample
module.exports = {
module: {
loaders: [{
test: /\.css?$/,
loaders: ['style', 'css']
}]
}
}
Once you have added the loaders to config, you can import your css files in you components
I am wondering how to set up an inline svg with webpack?
I am following the react-webpack-cookbook.
I have my webpack.config set up correctly with the file loader.
However the example shows using a background image like this:
.icon {
background-image: url(./logo.svg);
}
which works fine, but I want to have an inline svg image how do I do this to include my logo.svg inline in my react component?
import React, { Component } from 'react'
class Header extends Component {
render() {
return (
<div className='header'>
<img src={'./logo.svg'} />
</div>
);
}
};
export default Header
Actually Michelle's answer pointed me in the right direction, and that works nicely for loading an svg file with webpack and using it as your <img> src
However to actually get the inline svg, I needed to do the following:
Instead of file-loader use svg-inline-loader as your svg loader:
{ test: /\.svg$/, loader: 'svg-inline-loader' }
Then to load the svg inline in a component:
import React, { Component } from 'react'
import logo from "./logo.svg";
class Header extends Component {
render() {
return (
<div className='header'>
<span dangerouslySetInnerHTML={{__html: logo}} />
</div>
);
}
};
export default Header
It looks like there is an inline svg wrapper for react svg-inline-react which would be another option instead of the <div dangerouslySetInnerHTML={{__html: mySvg}} />
Here is a simple non-react solution.
Install Svg inline loader
In webpack.config.js add { test: /\.svg$/, loader: 'svg-inline-loader' }
In your js file import svg image and add it to a DOM element like so
import Svg from './svg.svg';
function component() {
const element = document.createElement('div');
element.innerHTML = Svg;
return element;
}
document.body.appendChild(component());
I hope my late answer will still be useful for someone, because I don't like any of abovementioned options.
The react-svg-loader webpack loader allows you to import SVG icons like JSX components:
import Logo from './logo.svg';
class App extends Component {
render() {
return (
<div className="App">
<Logo fill="red" className="logo" width={50} height={50} />
</div>
);
}
}
and minimum config looks like this:
{
test: /\.svg$/,
use: [
{
loader: "babel-loader"
},
{
loader: "react-svg-loader",
options: {
jsx: true // true outputs JSX tags
}
}
]
}
The best part is that it just outputs the svg file contents, without any extra wrappers and dangerouslySetInnerHTML in your code.
Old question, but I didn't see this solution anywhere so I decided to post it, hoping it will help someone.
If you want to be able to style those SVG icons, you might want to load them with the raw loader:
webpack.config.js:
{
test: /\.svg$/,
loader: 'raw-loader'
}
The import in my view:
import closeIcon from 'svg/ic_close_black_24px.svg';
The template (Mustache uses 3 brackets to insert the SVG data (URL)unencoded):
<button id="closeModal">
{{{closeIcon}}}
</button>
this way the SVG data will be inserted instead of the brackets and look like this:
<button id="closeModal">
<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
</button>
I'm using Backbone with Mustache template engine with Webpack 2.5.1
If I'm not mistaken, since you're using the file loader, you can utilize it in much the same way as any other require. Webpack will turn require("./logo.svg") into a path to a file, which it will emit when it bundles.
import React, { Component } from 'react'
import mySvg from './logo.svg'
class Header extends Component {
render() {
return (
<div className='header'>
<img src={mySvg} />
</div>
);
}
};
export default Header
Similar to another answer using React, there is also a handy Vue plugin as well.
vue-svg-loader just throw it in your configuration and start using. The nice thing is it will also run your svg through SVGO to optimize it.
Configuration
{
test: /\.svg$/,
loader: 'vue-svg-loader', // `vue-svg` for webpack 1.x
options: {
// optional [svgo](https://github.com/svg/svgo) options
svgo: {
plugins: [
{removeDoctype: true},
{removeComments: true}
]
}
}
}
Usage
<template>
<nav id="menu">
<a href="...">
<SomeIcon class="icon" />
Some page
</a>
</nav>
</template>
<script>
import SomeIcon from './assets/some-icon.svg';
export default {
name: 'menu',
components: {
SomeIcon,
},
};
</script>
Angular Solution (2019): Use svg-sprite-loader to combine SVGs into a single sprite that's lazy-loaded with your Webpack bundles.
Webpack
{
test: /\.svg$/,
use: [
'svg-sprite-loader',
'svgo-loader' // Optimize SVGs (optional)
]
}
HTML
<svg>
<use xlink:href="#arrow"/>
</svg>
Angular Component
export * from 'assets/images/icons/arrow.svg';
I use export (instead of import) to prevent the AOT compiler from removing the import during tree-shaking, while allowing for minimal code in the component, but you can use import if you prefer.
To use export in this way, you must configure the compiler to expect side effects from SVG files in package.json (i.e. you can not use "sideEffects": false). See the Webpack Tree Shaking Guide
"sideEffects": [
"*.svg",
],
#svgr/webpack (npm) is the inline svg loader that create-react-app uses.
Add the rule to your webpack config:
{
test: /\.svg$/,
use: ['#svgr/webpack'],
}
Then you can import svgs as React components:
import Star from './star.svg'
const App = () => (
<div>
<Star />
</div>
)
Folks who use svg-inline-loader and who stuck with "Cannot find module" error try to install babel-plugin-inline-react-svg and add it to the babel plugins:
"plugins": [
...
["inline-react-svg", {}]
],
...