Subscribe Us

React CSS Styling | React JS | Dark Watcher

 

React CSS Styling

There are three ways to style in React:

  1. Inline Styling
  2. CSS Stylesheets
  3. CSS Modules

Inline Styling

To inline style an element, we can make a Javascript Object, like this:

const App = () => {
  return (
    <>
      <h1 style={{ backgroundColor: "purple" }}>CodeWithHarry</h1>
    </>
  );
}

In this first curly brace is to write javascript and second is to make a javascript object. We can also write it like:

const App = () => {

  const h1Style = {
    backgroundColor: 'purple',
    color: 'white'
  }

  return (
    <>
      <h1 style={h1Style}>CodeWithHarry</h1>
    </>
  );
}

Note: CSS property name must be camelCase. background-color would be backgroundColor

CSS Stylesheets

You can save the whole CSS in a separate file with file extension .css and import it in your application. 

App.css

body {
  background-color: 'purple';
  color: 'white';
}

Here we are writing CSS, so we don't need to make JS Object or do it in camelCase. 

Index.js

Just import it like this:

import './App.css'

CSS Modules

In this you don't have to worry about name conflicts as it is component specific. The CSS is available only for the file in which it is imported. 

Make a file with extension .module.css, example: index.module.css

Make a new file index.module.css and insert some CSS into it, like this:

.button {
  background-color: 'purple';
  color: 'white';
}

Import it in component like this:

import styles from './index.module.css'; 

const Home = () => {
    return (
        <button className={styles.button}>Click me!</button>
    )
};

export default Home;

Post a Comment

0 Comments