How to use CSS styles in Reactjs


How to use CSS styles in Reactjs

Web app without CSS as to Tea without sugar. If you don’t know CSS , grab some CSS lesson from the WC3 school and come back. So how we use CSS in React apps ?

We have two options

  • Include regular CSS stylesheet file using import
  • Implement a functional component as Stylesheet

First option is look like simple go head and create a style.css file and add the following CSS style in int

.container{
 background-color: skyblue;
}
h2 {
   text-align: center;
}

Import the style sheet

Import the stylesheet as we import JS modules in React .

import './Styles.css'

Using the styles

Since it is a regular style sheet we can use it with className attribute as follow. A class file in style file start with period (.) and id is begins with hash (#). We can combine multiple class in a ClassName attribute using space.

Here is the sample style usage in render portion of a React ClassComponent

render() {
   return (
     <div className="container">
       <h1>This is a heading</h1>
     </div>
  );
}

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.