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.
1 | 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.
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import React from "react"; import './App.scss'; import sampleImg from './sample.jpg'; function App() { return ( <div classname="App"> <h3>Add sass or scss in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Meditor</a></h3> <div classname="img-card"> <img classname="img" src="{sampleImg}"> <div classname="card-body"> <div classname="card-title">Lorem ipsum</div> <div classname="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.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂