CSS in React

Styling is an essential part of any application. In React, you can style your app using CSS files and inline styles. This section will cover both methods.

Using CSS Files

You can import CSS files into your React components and use class names and IDs for styling, similar to HTML.

Example

import './App.css';

function App() {
  return (
    <>
      <a href="https://react.dev/" className="link">ReactJS</a>
      <a href="https://react.dev/" id="link">ReactJS</a>
    </>
  );
}

export default App;

CSS

/* App.css */
.link {
  text-decoration: none;
  color: #000;
}

#link {
  text-decoration: underline 1px wavy #808080;
  color: grey;
}
Warning

In JSX, the class attribute is replaced with className and attributes are written in camelCase.

Inline CSS in JSX

Inline styles can also be used in JSX. Instead of writing style attributes as strings, you use a JavaScript object to map style properties to values.

Example

function App() {
  return (
    <a 
      style={{ fontSize: '1.5em', color: 'purple' }} 
      href="https://vitejs.dev">
      Vite JS
    </a>
  );
}

export default App;

Using Variables for Inline Styles

You can also define a style object and use it in your JSX.

const heading = {
  color: 'red',
  textTransform: 'uppercase'
};

function App() {
  return (
    <>
      <h2 style={heading}>Vite App</h2>
    </>
  );
}

export default App;
Pitfall

Remember to write CSS properties in camelCase when using inline styles. For example, font-size becomes fontSize.

Task

Practice Styling in React

Objective: Create a React component with both external and inline styles.

  1. Create styles.css:

    .highlight {
        background-color: yellow;
        font-weight: bold;
    }
    
    #important {
        color: red;
        font-size: 2em;
    }
    
  2. Create and style a new component StyledComponent.jsx:

    import React from "react";
    import './styles.css';
    
    const StyledComponent = () => {
        const customStyle = {
            padding: '10px',
            border: '1px solid black'
        };
    
        return (
            <>
                <p className="highlight">This is a highlighted paragraph.</p>
                <p id="important">This is an important message.</p>
                <div style={customStyle}>This div has custom inline styles.</div>
            </>
        );
    };
    
    export default StyledComponent;
    
  3. Import and use StyledComponent in App.jsx:

    import React from "react";
    import StyledComponent from "./StyledComponent";
    
    const App = () => {
        return (
            <>
                <StyledComponent />
            </>
        );
    };
    
    export default App;
    

This task will help you practice using both external CSS files and inline styles in a React application.