How to add sass or scss in React
Today we’ll show you how to add sass or scss in React application. If you are using the `create-react-app` package in your react project then it is very easy to add sass or scss in the react app with three simple steps.
In this short article, we’ll use the npm package to configure sass/scss in the React application.
Steps to add sass or scss in React
1. Create a react app
Let’s create a simple react application using the `create-react-app` package. Run the following command to create a react app.
npx create-react-app react-node-sass-example
2. Install sass package
We have to install the node-sass package to use the `.sass` or `.scss` file in the react application. Run the following command to install the sass package.
npm i node-sass
Note: If you are getting an error like Error: Node Sass version 5.0.0 is incompatible with ^4.0.0. then install the [email protected] version. Run the following command to install the specific version.
`npm i [email protected]`
3. Create and import .scss file
After successful installation, we can create `.scss` or `.sass` file for component styling. Same as the `.css` file, we have to import it in the react component.
For the demonstration, let’s add the `App.scss` file in the `App.js` component to create an image card. Look at the following code.
App.scss
body {
margin: 30px;
font-family: Arial, Helvetica, sans-serif;
}
/* card style start */
.App {
.img-card {
width: 300px;
border-radius: 4px;
background: #f5f5f5;
color: #666;
overflow: hidden;
box-shadow: 0 2px 4px 0 rgba(0,0,0,0.2);
transition: 0.3s;
.img {
width: 100%;
height: 200px;
object-fit: cover;
}
.card-body {
padding: 15px;
.card-title {
font-size: 20px;
font-weight: 600;
}
.card-text {
margin-top: 10px;
}
}
}
.img-card:hover {
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
}
}
/* card style end */
App.js
import React from "react";
import './App.scss';
import sampleImg from './sample.jpg';
function App() {
return (
<div class="App">
<h3>Add sass or scss in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Meditor</a></h3>
<div class="img-card">
<img class="img" src={sampleImg}>
<div class="card-body">
<div class="card-title">Lorem ipsum</div>
<div class="card-text">Lorem ipsum dolor sit amet elit.</div>
</div>
</div>
</div>
);
}
export default App;
Output
Run the react application and check the image card output in the browser.
Output - How to add sass or scss in React - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂