In this tutorial, we’re gonna look at how to style a React Application (apply SCSS/CSS files to React Application) with Webpack.
Related Posts:
– Build & run React Application with Webpack – React Webpack example
– React Modal example
Goal
We had created a React Application like this:
Today we will know way to decorate it:
How to
Install Packages
We need style-loader, css-loader, sass-loader, node-sass for applying CSS, SCSS file:
1 2 3 4 5 6 7 8 9 10 |
{ ... "dependencies": { ... "style-loader": "0.20.3", "css-loader": "0.28.11", "sass-loader": "6.0.7", "node-sass":"4.8.3" } } |
Run cmd yarn install
to add these packages to our application.
Configure Webpack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
... module.exports = { ... module: { rules: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/ }, { test: /\.s?css$/, // scss & css files use: [ 'style-loader', 'css-loader', 'sass-loader' ] } ] }, ... }; |
Create Styles
– styles.scss imports all scss/css files:
1 2 3 4 5 6 7 8 |
@import './base/settings'; @import './base/base'; @import './components/container'; @import './components/header'; @import './components/action'; @import './components/button'; @import './components/notes'; @import './components/note'; |
– base/settings.scss contains global variables for styling colors or size:
1 2 3 4 5 6 7 |
$dark: #333745; $blue: #6699ff; $light: #d4d4d4; $s-size: 1.2rem; $m-size: 1.6rem; $l-size: 3.2rem; |
– base/base.scss is for base configuration such as font or background:
1 2 3 4 5 6 7 8 9 |
html { font-size: 62.5%; } body { background: $dark; font-family: Helvetica, Arial, sans-serif; font-size: $m-size; } |
– Each Component has corresponding SCSS file inside components folder.
– We also have container.scss and button.scss for useful class items that may be used frequently.
Add Styles to Components
To use the styles that we create in SCSS/CSS files, just put it as className
HTML attribute.
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import React from 'react'; const Note = (props) => ( <div className='note'> <p className='note__text' onClick={(e) => props.showNoteModal(props.note)}> {props.note} </p> <button className='button button--remove' onClick={(e) => props.deleteNote(props.note)}> Remove </button> </div> ); export default Note; |
In app.js, import styles.scss:
1 2 3 4 |
import ...; import './styles/styles.scss'; ReactDOM.render(<NoteApp />, document.getElementById('app')); |
Source code
For running:
– yarn install
– yarn run dev-server
or yarn run build
, then yarn run serve
.