CSS Modules
A CSS module is a simple CSS file but a key difference is by default when it is imported every class name and animation inside the CSS module is scoped locally to the component that is importing it also CSS file name should follow the format ‘filename.module.css’. This allows us to use a valid name for CSS classes without worrying about conflicts with other class names in your application.
To use CSS modules create a normal CSS file, import the module you have created from within your component using the syntax
import styles from './filename.module.css
Example :
Javascript
// Filename - App.js import React, { Component } from "react" ; import StudentList from "./StudentList" ; const App = () => { return ( <div> <StudentList name= "Ashank" classNo= "X" roll= "05" addr= "Kolkata, West Bengal" /> <StudentList name= "Samir" classNo= "Xi" roll= "09" addr= "Jalpaiguri, West Bengal" /> <StudentList name= "Tusar" classNo= "Xii" roll= "02" addr= "Howrah, West Bengal" /> <StudentList name= "Karishma" classNo= "ix" roll= "08" addr= "Mednipur, West Bengal" /> </div> ); }; export default App; |
Javascript
// Filename - StudentList.js import React, { Component } from "react" ; import style from "./StudentList.module.css" ; const StudentList = (props) => { const { name, classNo, roll, addr } = props; return ( <ul className={style.list}> <li className={style.details}>Name : {name}</li> <li className={style.details}> Class: {classNo} </li> <li className={style.details}>Roll: {roll}</li> <li className={style.details}> Address : {addr} </li> </ul> ); }; export default StudentList; |
CSS
/* Filename: StudentList.module.css */ .list { border : 2px solid green ; width : 40% ; list-style-type : none ; } .details { color : blue ; font-size : 23px ; } |
Output :
8 Ways to Style React Components
React is a JavaScript library for building user interfaces. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.
There are about eight different ways to style React JS components, there names and explanations of some of them are mentioned below.
- Inline CSS
- Normal CSS
- CSS in JS
- Styled Components
- CSS module
- Sass & SCSS
- Less
- Stylable
Here are a few examples to style React Components.
Table of Content
- Inline CSS
- Normal CSS
- CSS in JS
- CSS Modules
- Sass and SCSS
Contact Us