Loading...

Different Ways to Import CSS Files in React

10 Mins
Pravin Prajapati  ·   30 Dec 2024
Import-css-files-in-react
service-banner

We're all familiar with the common ways to link stylesheets to an HTML document: 1. external stylesheets, 2. internal styles, and 3. inline styles for importing CSS. These approaches are the cornerstone of CSS. They let developers separate concerns, manage design, and keep styles efficient across projects.

However, new and dynamic techniques broaden the CSS landscape for styling a single-page application (SPA) like a React project. Some methods align with traditional approaches. Others introduce new ideas for React's component-driven architecture. React offers options for various use cases and preferences. They range from modular stylesheets to inline styles in JavaScript.

Let's find ways to import CSS in React and style the new applications. These approaches can transform your workflow.

1. Importing External Stylesheets

React allows you to import external CSS files directly into your components. This approach is similar to linking a CSS file in an HTML document's <head> section, but you do it programmatically here.

Here's how to work with external stylesheets in React:

  1. Create a CSS file: Create a new CSS file in your project directory (e.g., style.css).
  2. Write your styles: Add your CSS rules and classes to the file.
  3. Import the CSS file: Use an import statement to bring the CSS file into your React component.

Here's an example:

import React from "react";
import "./Components/css/App.css"; // Import the external CSS file

function App() {
  return (
    
{/* Content goes here */}
); } export default App;

In this example, the CSS file is in the /Components/css folder and imported into App.js. The import "./Components/css/App.css" line, placed at the top of the file, ensures that the styles are applied to this component and any children using the same class names.

This method keeps your styling organized and allows you to reuse or apply the same CSS file across multiple components, maintaining a clean and modular structure in your project.

2. Apply Manual Inline Styles

You may have heard that inline styling isn't the best choice for maintainability, and in many cases, that's true. However, there are scenarios where using inline styles makes sense, especially in React. Since styles often reside within the same file as the component, maintainability concerns are less pronounced.

Here's a simple example of inline styling in React:

Inline styling example

While the above works, a more structured and reusable approach is to use style objects:

  1. Create~ an object to define styles for different elements.
  2. Apply these styles to elements using the style attribute, referencing the specific properties within the object.
import React from "react";

function App() {
  const styles = {
    main: {
      backgroundColor: "#f1f1f1",
      width: "100%",
    },
    inputText: {
      padding: "10px",
      color: "red",
    },
  };

  return (
    
); } export default App;

Here are two objects: the first is for the .main class, and the other is for the text input. Each sub-object has style rules similar to those in an external stylesheet. These styles are then applied to elements through the style attribute. This is done by referencing their properties (e.g., styles.main).

3. Integration with CSS Modules

Even though some may have overlooked them, CSS modules are still an excellent choice for React styling. Use CSS modules with your React workflow to get scoped class names.

Let's break it down: CSS Modules allow you to use identical class names across different files without causing more conflicts in the script. Each class name is given a unique, programmatically generated name, ensuring that styles remain scoped to the associated component. This feature is convenient in larger applications where naming collisions can become an issue.

How CSS Modules Work

A CSS Module file is a standard CSS file with a .module.css extension. Here's the basic workflow:

  1. Create a CSS Module file: Name the file with the .module.css extension (e.g., styles.module.css).
  2. Import the Module: Bring the module into your React component using an import statement.
  3. Apply Styles: Use the className attribute to assign styles by referencing the specific class from the imported module.
Example

Here's a simple example of CSS Modules in action:

/* styles.module.css */
.font {
  color: #f00;
  font-size: 20px;
}
import React from "react";
import styles from "./styles.module.css"; // Import the CSS Module

function App() {
  return (
    

Hello World

// Apply the style ); } export default App;

In this example:

  • The CSS file styles.module.css contains a .font class definition.
  • When imported into App.js, the styles are applied to the <h1> tag using className={styles.font}.
Why Use CSS Modules?
  • Scoped Styles: Each class name is uniquely generated, avoiding file conflicts.
  • Maintainability: Clear organization by associating styles with specific components.
  • Flexibility: You can still use global styles for shared themes while keeping component-specific styles scoped.

CSS Modules are an excellent choice for large-scale React projects, balancing modularity and maintainability.

CSS Modules are an excellent choice for large-scale React projects, balancing modularity and maintainability.

4. Styled-Components

While JSX seamlessly combines HTML and JavaScript, what about CSS? Styled Components offer a powerful way to integrate CSS directly into your components.

Styled Components is a third-party library that allows you to create reusable, custom HTML components with predefined CSS properties. These styled components can be used anywhere in your project, making your styling modular and scoped.

Key Concept: Template Literals

Styled Components leverage a feature introduced in ES6 called template literals, which enables custom string interpolation rules. This feature and CSS syntax form the foundation for defining styled components.

Installation

Since Styled Components is an npm package, you'll need to install it first:

npm install styled-components How to use it?

Once installed, you can use Styled Components in your React app like this:

import styled from "styled-components";

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

const Container = styled.section`
  margin: 10px;
`;

function App() {
  return (
    
      Hello World!
    
  );
}

export default App;
Explanation
  • Custom Tags: In the example, two custom components are created: Container and Title.
  • Styled Components: These are styled versions of standard HTML tags (section and h1), with their CSS properties defined directly using template literals.
  • Reusable and Scoped: The custom components encapsulate their styles, making them reusable across your app while avoiding style conflicts.
Why Use Styled Components?
  • CSS-in-JS: Integrates CSS directly into JavaScript, keeping styles close to the components to which they belong.
  • Dynamic Styling: Easily use props to adjust styles dynamically.
  • Scoped Styles: Eliminates the need for class name conventions and avoids style leakage.
  • Maintainable: Encourages modular code by encapsulating styles within components.

Styled Components offer a modern, flexible approach to styling React applications. They seamlessly bridge the gap between JavaScript and React.

5. Utility-First CSS with Tailwind CSS

Tailwind CSS is a popular utility-first framework that enables you to style components directly within your JSX using predefined utility classes. Instead of writing custom CSS rules, you can rapidly build interfaces by composing styles from Tailwind's extensive library of classes.

How It Works

With Tailwind CSS, you apply styles directly to elements using class attributes in JSX. Each class corresponds to a specific CSS rule, making it highly expressive and easy to use.

Installation

To use Tailwind CSS in your React project, you first need to install and configure it:

npm install tailwindcss postcss autoprefixer
npx tailwindcss init
Set up the Tailwind configuration:

In the generated tailwind.config.js file, configure your content paths to enable the purging of unused styles:

module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};
Include Tailwind in your CSS:

Add the Tailwind directives to your main CSS file:

@tailwind base;
@tailwind components;
@tailwind utilities;
Start styling in your JSX:

Tailwind is now ready to use in your React project.

Example

Here's a simple example of using Tailwind utility classes:

function MyComponent() {
  return 
Hello, World!
; } export default MyComponent;
Key Features of Tailwind CSS
  • Utility-First Classes: Style elements directly with meaningful utility classes like text-blue-500, bg-gray-200, or p-4.
  • Customizable: Easily extend the default styles in the Tailwind configuration file to match your design system.
  • Responsive Design: Tailwind includes built-in responsive utilities, allowing you to add breakpoints (e.g., sm:, md:, lg:) effortlessly.
  • Productivity: Eliminates context-switching between CSS files and JSX, speeding up development.
Why Choose Tailwind CSS?
  • Efficiency: Quickly prototype designs without writing custom CSS.
  • Consistency: Ensures uniformity across the app by relying on a shared design framework.
  • Scalability: Tailwind's utility classes reduce CSS bloat and help manage styles in large-scale applications.

Tailwind CSS is an excellent choice for developers prioritizing speed, consistency, and a robust, utility-first approach to styling.

6. SCSS Modules

SCSS (Sass) is a CSS preprocessor that extends standard CSS with advanced features like variables, nesting, mixins, and more. When combined with CSS Modules, SCSS provides the benefits of scoped styling and Sass's power, making it a fantastic choice for modular and maintainable styles in React applications.

How It Works SCSS Modules work similarly to CSS Modules but use the .module.scss extension instead. Let's walk through the process:
  • Create an SCSS Module: Create a file with the .module.scss extension (e.g., styles.module.scss).
  • Define Styles: Write your styles using SCSS syntax, including variables and nesting.
  • Import and Apply: You can import the SCSS Module into your React component and apply the styles using the className attribute.
Example

Here's a simple example of SCSS Modules in action:

/* styles.module.scss */
$primary-color: blue;

.myClass {
  color: $primary-color;
  font-size: 20px;

  &:hover {
    color: darkblue;
  }
}
import React from "react";
import styles from "./styles.module.scss"; // Import the SCSS Module

function MyComponent() {
  return 
Hello, World!
; } export default MyComponent;

If SCSS isn't already configured in your React app, install the necessary package:

npm install sass

After installation, React will natively recognize .scss files, and you can start using SCSS Modules in your project.

7. Emotion

Emotion is a versatile library for styling React applications, similar to Styled Components. It supports both styled-components and CSS-in-JS approaches, offering flexibility and performance.

Example

Here's an example using Emotion's css prop for inline styling:

/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react";

const style = css`
  color: blue;
`;

function MyComponent() {
  return 
Hello, World!
; } export default MyComponent;
Key Features
  • CSS-in-JS: Write styles directly within JavaScript for modular and scoped styling.
  • Dynamic Styling: Easily adapt styles using props or variables.
  • Flexible API: Use the css prop or create styled components for reusable styles.
Installation

To get started with Emotion, install it using npm:

npm install @emotion/react

Team React Suggestions for New Developers

The React team has recently suggested some important recommendations related to the development process for next-generation developers. These reflect the changing web development landscape and the need for better tools. Here are the four key recommendations suggested by the team:

1. Move Away from the Create React App (CRA)

The React team no longer recommends using Create React App (CRA) as the default setup tool for new projects. While CRA was introduced to simplify the initial setup process for React applications, its one-size-fits-all approach does not meet the diverse needs of modern development.

You often need more flexibility than CRA can provide. This leads to a complex "eject" process to modify configurations. Next.js, Snowpack, and Parcel are now preferred. They meet project needs. They have features like server-side rendering, static site generation, and better performance.

2. Try to Adopt Statically Extracted Styles

The React team prefers statically extracted styles over CSS-in-JS solutions. Statically extracted styles improve performance. They let browsers cache CSS files efficiently, leading to faster load times. This approach enhances maintainability. It organizes styles in separate files, which makes debugging easier. Developers should define CSS in traditional stylesheets or use preprocessors like SCSS. This allows them to use advanced features while keeping a clear structure.

3. Use Inline Styles for Dynamic Values

Inline styles are recommended for dynamic styling based on component state or props. This method allows you to apply styles directly within JSX, simplifying code and ensuring that styles are scoped correctly without conflicts.

4. Implement Prop Types

Prop Types are now an official recommendation from the React team. They help document components by specifying the expected prop data types. This makes it easier for other developers to use them correctly. This practice helps catch errors and contributes to cleaner and more maintainable code.

You can enhance workflow, improve application performance, and create more maintainable codebases. The shift from CRA to more customizable options reflects a broader trend in the JavaScript ecosystem that prioritizes flexibility and efficiency in development practices.

Essence

Choosing the correct method for styling your React application depends on your needs and preferences. Whether you opt for traditional CSS, CSS Modules, Styled Components, or Tailwind CSS, knowing the strengths and weaknesses of each will help you make the right decisions that improve your development workflow experience.

Feel free to contact Elightwalk Technology for guidance on your new development project. For more information, visit our blog page, where our developers share tips and best practices for styling React applications.

If you need professional help with React application development, hire ReactJs developer. Our team of experienced developers can provide valuable insights and assistance to ensure your project's success!

FAQs about Import CSS Files

How do I import external CSS files in React?

What are CSS Modules, and how do I use them in React?

Can I use inline styles in React?

How do I integrate Tailwind CSS in a React project?

What is Styled Components, and how does it work in React?

How do I add SCSS support in a React project?

Pravin Prajapati
Full Stack Developer

Expert in frontend and backend development, combining creativity with sharp technical knowledge. Passionate about keeping up with industry trends, he implements cutting-edge technologies, showcasing strong problem-solving skills and attention to detail in crafting innovative solutions.

Most Visited Blog

Best 11 React Carousel Component Libraries
We present the best 11 React Carousel Component Libraries to improve the UI/UX designs for your next web development project. Improve the user experience by adding dynamic and interactive carousel components to your website or application. Choose the perfect carousel library for your project with the right expert guidance!
What is ReactJs Development?
This comprehensive guide walks you through various facets of React JS development, including its library versus framework debate, harnessing Hooks for state management, leveraging the Context API, mastering form creation and event handling, and embracing the latest trends in React JS development.
What is ReactJs? Key Features, Benefits and More Guide

If you're new to React or want to learn more, this 'Introduction to React JS' article will teach you all the essential stuff. It's meant for beginners, but even experienced React developers can use it as a reference guide.