---
title: Bitovi Academy - Styling in React
description: Learn about different ways to apply CSS styles in React applications.
---

- ![AI implementation](https://www.bitovi.com/hubfs/AIConsultingIcon.svg)
  
  [AI implementation](https://www.bitovi.com/services/ai-consulting?hsLang=en-us)
- ![Systems engineering](https://www.bitovi.com/hubfs/icon%20-%20backend.svg)
  
  [Systems engineering](https://www.bitovi.com/services/systems-engineering-consulting?hsLang=en-us)
- ![Project management](https://www.bitovi.com/hubfs/icon%20-%20PM.svg)
  
  [Project management](https://www.bitovi.com/services/agile-project-management-consulting?hsLang=en-us)
- ![Product design](https://www.bitovi.com/hubfs/icon%20-%20design.svg)
  
  [Product design](https://www.bitovi.com/services/product-design-consulting?hsLang=en-us)
- ![Frontend development](https://www.bitovi.com/hubfs/icon%20-%20frontend.svg)
  
  [Frontend development](https://www.bitovi.com/services/frontend-development-consulting?hsLang=en-us)
- [View more
  
  →
  
  ](https://www.bitovi.com/digital-consulting-services?hsLang=en-us)

We're Experts in...

- [JavaScript](https://www.bitovi.com/services/frontend/javascript-consulting?hsLang=en-us)
- [AI training](https://www.bitovi.com/ai-training-for-software-engineers?hsLang=en-us)
- [Angular](https://www.bitovi.com/services/frontend/angular-consulting?hsLang=en-us)
- [Design Systems](https://www.bitovi.com/services/axure-figma-migration?hsLang=en-us)
- [React](https://www.bitovi.com/services/frontend/react-consulting?hsLang=en-us)
- [Temporal](https://www.bitovi.com/services/backend/temporal-consulting?hsLang=en-us)
- [React Native](https://www.bitovi.com/services/frontend/react-consulting/react-native?hsLang=en-us)
- [Node.js](https://www.bitovi.com/services/backend/nodejs-consulting-1?hsLang=en-us)

Showcase

![Yum! Brands](https://www.bitovi.com/hubfs/yum-showcase-link-1.png)

[View case study](https://www.bitovi.com/en/bitovi-yum-case-study?hsLang=en-us)

More Projects

- [![Levi's](https://www.bitovi.com/hubfs/levis.svg)](https://www.bitovi.com/web-application-consulting-work/levis-ecommerce-responsive-redesign?hsLang=en-us)
- [![Christie's International Real Estate](https://www.bitovi.com/hubfs/christies.svg)](https://design.bitovi.com/christies)
- [![BAFS](https://www.bitovi.com/hubfs/bafs.svg)](https://www.bitovi.com/ux-design-consulting/ux-case-studies/bafs-ppp?hsLang=en-us)
- [View more
  
  →
  
  ](https://www.bitovi.com/our-software-consulting-work?hsLang=en-us)

Open Source Tools

We build powerful tools and open source them to support the community.

[See what we've built →](https://www.bitovi.com/open-source?hsLang=en-us)

- [![Blog](https://www.bitovi.com/hubfs/icon%20-%20blog.svg)
  
  BlogWe post about perfecting software delivery
  
  ](https://bitovi.com/blog)
- [![Partnerships](https://www.bitovi.com/hubfs/Handshake-1.svg)
  
  PartnershipsLearn about Bitovi's technology partners
  
  ](https://www.bitovi.com/partnerships?hsLang=en-us)
- [![Academy](https://www.bitovi.com/hubfs/limbo/icons/icon-academy.svg)
  
  AcademyFree courses to build delivery skills
  
  ](https://www.bitovi.com/academy/?hsLang=en-us)
- [![Open source tools](https://www.bitovi.com/hubfs/icon%20-%20open%20source.svg)
  
  Open source toolsUse our tools or contribute to our open source mission.
  
  ](https://www.bitovi.com/open-source?hsLang=en-us)

Let's Connect

- [![Discord](https://www.bitovi.com/hubfs/DiscordLogo.svg)
  
  Discord
  
  ](https://discord.gg/J7ejFsZnJ4)
- [![LinkedIn](https://www.bitovi.com/hubfs/LinkedinLogo.svg)
  
  LinkedIn
  
  ](https://www.linkedin.com/company/bitovi/)
- [![GitHub](https://www.bitovi.com/hubfs/GithubLogo.svg)
  
  GitHub
  
  ](https://github.com/bitovi/)

![Eggbot](https://www.bitovi.com/hubfs/build_assets/bitovi-limbo-cms-react/338/js_client_assets/assets/eggbot-LTGhdSGL.png)

Name *

Work Email *

Phone

What's your project?

Send

### Contact Us

(312) 620-0386contact@bitovi.com

[Bitovi](https://www.bitovi.com/?hsLang=en-us)

- [Services](https://www.bitovi.com/services?hsLang=en-us)
- [Client Work](https://www.bitovi.com/client-work?hsLang=en-us)
- [Our Team](https://www.bitovi.com/about?hsLang=en-us)
- [Open Source](https://www.bitovi.com/open-source?hsLang=en-us)
- [Blog](https://www.bitovi.com/blog?hsLang=en-us)
- [Academy](https://www.bitovi.com/academy/?hsLang=en-us)

[Contact Us](https://www.bitovi.com/contact?hsLang=en-us)

- [ Advanced JavaScript ](https://www.bitovi.com/academy/learn-advanced-javascript.html?hsLang=en-us)
- [ DOM and jQuery ](https://www.bitovi.com/academy/learn-dom-jquery.html?hsLang=en-us)
- [ Debug JavaScript ](https://www.bitovi.com/academy/learn-to-debug-javascript.html?hsLang=en-us)
- [ Learn TypeScript ](https://www.bitovi.com/academy/learn-typescript.html?hsLang=en-us)
- [ Learn React ](https://www.bitovi.com/academy/learn-react-vite.html?hsLang=en-us) 
    - [ Introduction to React ](https://www.bitovi.com/academy/learn-react-vite/intro-to-react.html?hsLang=en-us)
    - [ Setting Up Your Environment ](https://www.bitovi.com/academy/learn-react-vite/setting-up-your-environment.html?hsLang=en-us)
    - [ Introduction to JSX ](https://www.bitovi.com/academy/learn-react-vite/intro-to-jsx.html?hsLang=en-us)
    - [ Building Components ](https://www.bitovi.com/academy/learn-react-vite/components.html?hsLang=en-us)
    - [ Passing Props ](https://www.bitovi.com/academy/learn-react-vite/props.html?hsLang=en-us)
    - [ Routing in React ](https://www.bitovi.com/academy/learn-react-vite/routing.html?hsLang=en-us)
    - [ Styling in React ](https://www.bitovi.com/academy/learn-react-vite/styling-in-react.html?hsLang=en-us)
    - [ Managing State in React ](https://www.bitovi.com/academy/learn-react-vite/stateful-hooks.html?hsLang=en-us)
    - [ Making HTTP Requests ](https://www.bitovi.com/academy/learn-react-vite/making-http-requests.html?hsLang=en-us)
    - [ Creating Nested Routes ](https://www.bitovi.com/academy/learn-react-vite/nested-routes.html?hsLang=en-us)
    - [ Handling User Inputs and Forms ](https://www.bitovi.com/academy/learn-react-vite/controlled-vs-uncontrolled.html?hsLang=en-us)
    - [ Testing in React ](https://www.bitovi.com/academy/learn-react-vite/testing.html?hsLang=en-us)
- [ Learn Web Components ](https://www.bitovi.com/academy/learn-web-components.html?hsLang=en-us)
- [ Agile Program Management With Jira ](https://www.bitovi.com/academy/learn-agile-program-management-with-jira.html?hsLang=en-us)
- [ Learn RxJS ](https://www.bitovi.com/academy/learn-rxjs.html?hsLang=en-us)
- [ Giving a Training ](https://www.bitovi.com/academy/training.html?hsLang=en-us)
- [ Learn Technology Consulting ](https://www.bitovi.com/academy/learn-technology-consulting.html?hsLang=en-us)
- [ Learn React ](https://www.bitovi.com/academy/learn-react.html?hsLang=en-us)
- [ Learn NgRx ](https://www.bitovi.com/academy/learn-ngrx.html?hsLang=en-us)
- [ Learn Graphql ](https://www.bitovi.com/academy/learn-graphql.html?hsLang=en-us)
- [ Learn Docker ](https://www.bitovi.com/academy/learn-docker.html?hsLang=en-us)
- [ Learn CanJS ](https://www.bitovi.com/academy/learn-canjs.html?hsLang=en-us)
- [ Learn Angular ](https://www.bitovi.com/academy/learn-angular.html?hsLang=en-us)
- [ Advanced TypeScript ](https://www.bitovi.com/academy/advanced-typescript.html?hsLang=en-us)

[View More Courses](https://www.bitovi.com/academy/#courses) [ ]

# Styling in React `page`

Learn about different ways to apply CSS styles in React applications.

## Overview

There is no prescribed approach for styling React apps. It’s entirely possible to style components using regular CSS. This approach works fine for many applications, especially smaller ones.

However, as your application grows in complexity, you might encounter challenges with style management. For instance, CSS written for one component can unintentionally affect other parts of your application.

The community has built several styling options. We will be using CSS Modules as it is one of the most popular styling libraries and is very approachable for anyone that is used to styling in plain CSS. CSS Modules offer a way to write CSS that’s scoped to individual components, thus preventing style clashes and maintaining a cleaner codebase.

## Objective 1: Applying style with CSS Modules

In this section, we will:

- Review how plain CSS works in React applications
- Set up CSS Modules
- Create a component-specific stylesheet
- Apply styles to a component

### Reviewing how plain CSS works

In a standard React application using regular CSS, styles are global. This means that any style you define can potentially affect any element in your application that matches the style’s selector.

Let’s imagine that we have two components in our application: `<BlogPost>` and `<UserProfile>`. Both of them feature an avatar image, one for the author of a post and the other for the signed-in user.

Here’s what the `BlogPost.css` file might look like:

```
.avatar {
  float: left;
  margin-right: 10px;
}
```

And the `BlogPost.tsx` component:

```
import React from 'react';
import './BlogPost.css';

const BlogPost: React.FC = ({ authorAvatar, content }) => {
  return (
    <article>
      <img
        alt="Headshot showing…"
        className="avatar"
        src={authorAvatar}
      />
      <p>{content}</p>
    </article>
  );
}
```

Here’s what the `UserProfile.css` file might look like:

```
.avatar {
  border-radius: 50%;
  height: 100px;
  width: 100px;
}
```

And the `UserProfile.tsx` component:

```
import React from 'react';
import './UserProfile.css';

const UserProfile: React.FC = () => {
  return (
    <img
      alt="User avatar showing…"
      className="avatar"
      src="user-profile.jpg"
    />
  );
}
```

What will the final CSS be?

In this case, the two style declarations combined will be applied to both images:

```
.avatar {
  border-radius: 50%;
  float: left;
  height: 100px;
  margin-right: 10px;
  width: 100px;
}
```

This is no good! When someone edits one component, it looks like they’re only changing the styles for that single component, but in fact they are changing any instance where that `class` name is used globally throughout the entire application.

Let’s solve this!

### Scoped stylesheet

CSS Modules works like regular CSS, but the class names are randomized to prevent conflicts between components. When using CSS Modules, if multiple components implement a `.avatar` class, those classes will be unique and conflict-free because CSS Modules will rename each class with a unique random string like `.avatar_R8f2`.

For example, these styles in a CSS module:

```
/* BlogPost.css */
.avatar {
  float: left;
  margin-right: 10px;
}
```

Will be converted into the following:

```
/* BlogPost.module.css */
.avatar_R8f2 {
  float: left;
  margin-right: 10px;
}
```

The standard procedure with CSS Modules is to create a stylesheet for each component. That stylesheet is placed in the same folder as the component. In order to identify the file as a CSS Module, the filename should end with `.module.css`. The file structure for a BlogPost component will look like the following:

- BlogPost 
    - BlogPost.module.css
    - BlogPost.test.tsx
    - BlogPost.tsx
    - index.ts

Note that CSS Modules cannot rename HTML tags, so all of your styling should use classes to avoid unexpected styling bugs. The following will apply to all `img` elements in the project and should be avoided.

```
/* Don't do this with CSS Modules as tag names can not be randomized */
img {
  float: right;
}
```

### Importing and applying styles

During the build process, the CSS classes will be randomized and added to a global stylesheet. The randomized class names are imported into components as an object where the key is the original class and the value is the new, randomized string.

Here’s an example of what the JS object imported from `BlogPost.module.css` might look like:

```
{ avatar: "avatar_R8f2" }
```

In order to add the `.avatar` class to a component, import the CSS Modules styling object and apply the class using the original class name as the key. Note the HTML `class` attribute is renamed to `className` in JSX because `class` is a reserved word in JavaScript.

```
import React from 'react';
import styles from './BlogPost.module.css`

const BlogPost: React.FC = ({ authorAvatar, content }) => {
  return (
    <article>
      <img
        alt="Headshot showing…"
        className={styles['avatar']}
        src={authorAvatar}
      />
      <p>{content}</p>
    </article>
  );
}
```

### Exercise 1

Now that we've learned to apply styling in React with CSS Modules, it's time to practice by styling a link in the Home component. You'll bring in a `Link` component from React Router.

### Install CSS Modules

Already done! Vite, our build tool, ships with first-class CSS Modules support. Vite also supports a few [other styling options](https://vitejs.dev/guide/features#css) out of the box.

### Setup

We've created some CSS for this exercise. Create a CSS Modules file and copy the following styles into it.

✏️ Create **src/pages/Home/Home.module.css** and update it to be:

```
a {
    display: inline-block;
    margin-bottom: 0;
    font-weight: normal;
    text-align: center;
    vertical-align: middle;
    touch-action: manipulation;
    cursor: pointer;
    background-image: none;
    border: 1px solid transparent;
    white-space: nowrap;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    border-radius: 4px;
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
    padding: 10px 16px;
    font-size: 18px;
    line-height: 1.3333333;
    border-radius: 6px;
}

a:focus {
    color: #fff;
    background-color: #286090;
    border-color: #122b40;
    text-decoration: none;
}

a:hover {
    color: #fff;
    background-color: #286090;
    border-color: #204d74;
    text-decoration: none;
}

a:active {
    color: #fff;
    background-color: #204d74;
    border-color: #122b40;
    text-decoration: none;
}
```

TODO: Clean up the extraneous styles in the code above. [Chasen can handle this.]

### Verify

✏️ Update **src/pages/Home/Home.test.tsx** to be:

```
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it } from 'vitest';

import Home from './Home';

describe('Home component', () => {
  beforeEach(() => {
    render(
      <MemoryRouter>
        <Home />
      </MemoryRouter>
    );
  });

  it('renders the image with correct attributes', () => {
    const image = screen.getByAltText(/Restaurant table with glasses./i);
    expect(image).toBeInTheDocument();
    expect(image).toHaveAttribute('width', '250');
    expect(image).toHaveAttribute('height', '380');
  });

  it('renders the title', () => {
    const titleElement = screen.getByText(/Ordering food has never been easier/i);
    expect(titleElement).toBeInTheDocument();
  });

  it('renders the description paragraph', () => {
    const description = screen.getByText(/We make it easier/i);
    expect(description).toBeInTheDocument();
  });

  it('renders the link to the restaurants page', () => {
    const link = screen.getByRole('link', { name: /choose a restaurant/i });
    expect(link).toBeInTheDocument();
    expect(link).toHaveAttribute('href', '/restaurants');
  });
});

```

### Exercise

- Update the styles in `Home.module.css` to be usable as a CSS Module.
- Update the `<Home>` component to include a styled link: 
    - Use `<Link>` (from the previous section!) to create a link to the `/restaurants` page.
    - Import the `styles` from `Home.module.css` and apply them to the new link.

### Solution

Click to see the solution

✏️ Update **src/pages/Home/Home.module.css** to be:

```
.chooseButton {
    display: inline-block;
    margin-bottom: 0;
    font-weight: normal;
    text-align: center;
    vertical-align: middle;
    touch-action: manipulation;
    cursor: pointer;
    background-image: none;
    border: 1px solid transparent;
    white-space: nowrap;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    border-radius: 4px;
    color: #fff;
    background-color: #337ab7;
    border-color: #2e6da4;
    padding: 10px 16px;
    font-size: 18px;
    line-height: 1.3333333;
    border-radius: 6px;
}

.chooseButton:focus {
    color: #fff;
    background-color: #286090;
    border-color: #122b40;
    text-decoration: none;
}

.chooseButton:hover {
    color: #fff;
    background-color: #286090;
    border-color: #204d74;
    text-decoration: none;
}

.chooseButton:active {
    color: #fff;
    background-color: #204d74;
    border-color: #122b40;
    text-decoration: none;
}
```

✏️ Update **src/pages/Home/Home.tsx** to be:

```
import HeroImage from "place-my-order-assets/images/homepage-hero.jpg"
import { Link } from "react-router-dom"
import styles from "./Home.module.css"

const Home: React.FC = () => {
    return (
        <div className="homepage" style={{ margin: "auto" }}>
            <img
                alt="Restaurant table with glasses."
                height="380"
                src={HeroImage}
                width="250"
            />

            <h1>Ordering food has never been easier</h1>

            <p>
                We make it easier than ever to order gourmet food from your favorite
                local restaurants.
            </p>

            <p>
                <Link className={styles.chooseButton} to="/restaurants">
                    Choose a Restaurant
                </Link>
            </p>
        </div>
    )
}

export default Home
```

**Having issues with your local setup?** See the solution in [StackBlitz](https://stackblitz.com/fork/github/bitovi/academy/tree/main/exercises/react-vite/07-styling-in-react/01-solution?file=src/pages/Home/Home.tsx) or [CodeSandbox](https://codesandbox.io/p/devbox/github/bitovi/academy/tree/main/exercises/react-vite/07-styling-in-react/01-solution?file=src/pages/Home/Home.tsx).

## Next steps

In the next section, we'll learn to manage state.

###### On this page...

###### Get help

If you need [help](https://discord.gg/J7ejFsZnJ4) with an exercise, please reach out to us on [Discord](https://discord.gg/J7ejFsZnJ4)

If you find a bug, please [create an issue](https://github.com/bitovi/academy/issues/new) or email [contact@bitovi.com](mailto:contact@bitovi.com?Subject=Training%20Suggestion)

## Join the Bitovi Newsletter

 Do you want to receive updates about new Bitovi Academy courses, Bitovi open source projects, and dev community news? If so, please provide your email. We won’t spam you or give it away for any reason!  
*By providing your email you agree to receive communications from Bitovi*

![](https://bitovi.github.io/academy/static/img/close.svg)

```json
{
     "@context": "http://schema.org",
     "@type": "Organization",
     "mainEntityOfPage":{
          "@type":"WebPage",
          "@id":"https://www.bitovi.com/academy/learn-react-vite/styling-in-react.html",
          "description": "Learn about different ways to apply CSS styles in React applications. 
"
     },
     "url": "http://bitovi.com",
     "logo": "https://www.bitovi.com/hubfs/bitovi-logo-23-1.svg",
     "image": "https://www.bitovi.com/hubfs/bitovi-logo-x2.png",
     "name": "Bitovi Web App Consulting",
     "alternateName": "Bitovi",
      "naics": "541511",
      "description": "Bitovi is a UX, UI design and front-end JavaScript development consulting company",
     "address": {
          "@type": "PostalAddress",
          "streetAddress": "1134 Pine Tree Lane ",
          "addressLocality": "Libertyville",
          "addressRegion": "IL",
          "addressCountry": "United States",
          "postalCode": "60048"
     },
     "areaServed": {
          "@type": "GeoCircle",
          "geoMidpoint": {
               "@type": "GeoCoordinates",
               "latitude": "41.8781",
               "longitude": "87.6298"
          },
          "geoRadius": "5000 km"
     },
     "telephone": "312-620-0386",
     "email": "contact@bitovi.com",
     "sameAs": [
          "https://www.facebook.com/BitoviLLC/",
          "https://twitter.com/bitovi",
          "https://www.linkedin.com/company/bitovi"
     ]
}
```