CSS in react

React components can be styled using below method.
  • Inline
  • External css file - global css
  • CSS modules - locally scoped css
  • Styled components

Inline styles

As you can see in below example, you can use style attribute and pass the java script objects inside { }

<span style={{color:'red'}}>React components</span> can be styled using inline or external css method.

External styles

External css files can be imported using syntax as mentioned below. All css rules in such file are global.

import "./stylesheet.css";
<div className='banner'>This div is styled using external css file</span>

CSS modules

This method is similar to external css. The main difference is that styles defined in modules are not global. All you need to do is create a file with extension .module.css and write css rules in this file. There are certain restrictions on such file. e.g. You can not target elements based on tags but you can target elements based on classes.

import styles from "./HomePage.module.css";

//here .banner is the class defined in module.css file.

<div className={styles.banner}>This div is styled using css module</span>

Styled Components

You will need to install below npm package.
npm install styled-components

import styled from 'styled-components'

//create a styled button component
const MyButton = styled.button`
  background: red;

    <MyButton>This is a styled button</MyButton>

Web development and Automation testing

solutions delivered!!