Nearby lessons

12 of 44

🎨 ReactJS – Styling Components

📌 How to Style Components?

How to Style Components in React?

In React, there are multiple ways to style components. The most common methods are:

  1. Inline Styles
  2. CSS Stylesheets (External CSS)
  3. CSS Modules
  4. CSS-in-JS Libraries (like styled-components)

Let's explore Inline Styles and External Stylesheets with examples.

1. Inline Styles

Inline styles are applied using the style attribute. The value must be a JavaScript object.

Since JavaScript objects use curly braces, in JSX we write inline styles inside two curly braces {{}}.

Important: Inline styles cannot use pseudo-classes like :hover, :active, etc.

Property names must use camelCase, e.g., backgroundColor instead of background-color.

React Playground
import StyleComponent from './StyleComponent.jsx'
export default function App(props) {
  return (
    <>
       <StyleComponent/>
    </>
  );
}

2. CSS Stylesheets (External CSS)

You can create a separate .css file and import it into your component.

Important:

  • Use className instead of class.
  • Follow camelCase when writing JSX attributes.
  • It’s a convention to name the CSS file same as the component.

We can also apply conditional styles using props or state.

React Playground
import CSSStylesheetComponent from './CSSStylesheet.jsx';
export default function App(props) {
  return (
    <>
      <CSSStylesheetComponent check={true} />
    </>
  );
}

⚠️ Problem with External CSS

When two components use the same class name in different CSS files, styles may conflict and override each other.

This is a limitation of global CSS styles.

React Playground
import Stylesheet1 from './Stylesheet1.jsx';
import Stylesheet2 from './Stylesheet2.jsx';
export default function App(props) {
  return (
    <>
        <Stylesheet1/>
        <Stylesheet2/>
    </>
  );
}

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - CSS Modules