• Articles
  • Tutorials
  • Interview Questions

How to Add Style in React

How to Add Style in React

In this blog, we’ll explore different methods to add style in React. We’ll also explore how to implement them effectively, so you can take your UI to the next level.

To cover the prerequisites of React Native check out our Youtube Channel on React Native Tutorial:

Video Thumbnail

Setting up your React application

Let’s go through some fundamental project setup procedures to apply style with React. You can manually set up your React project with webpack or parcel, or you can utilize a create-react-app. After setting up your project, you can begin giving your React Js style components .

Here are the basic steps to set up a React project for React Js styling.

  1. Create your React project using Create React App or a build tool like webpack or Parcel.
  2. Import a CSS/style sheet into your component. You have a few options
  • Import a CSS file
import './styles.css';
  • Import directly in your JSX
const divStyle = {
  color: "blue" 
};
<div style={divStyle}>Hello World!</div>
  1. Add CSS class names to your JSX elements.
<div className="header"> 
  <h1>Hello!</h1>
</div>
  1. Define your CSS styles, either
    • In an external .css file
    • With inline styles in your JSX
    • In a CSS library
  1. Apply the styles to your components by linking your CSS files, using inline styles, or using the classes from a CSS library.

Finally, the essential steps encompass generating your project, incorporating styles into your components, assigning class Names to your JSX, specifying your styles, and subsequently employing the mentioned styles. 

Styling React Components with Inline Styling

Styling React Components with Inline Styling

Inline React Js styling is the simplest way to add style to your React components. You can use the style attribute and pass in an object with React Js CSS in Js properties and values. While inline styling is straightforward, it can make your code harder to read if you have a lot of CSS properties.

function Example() {
  const style = {
    color: "blue",
    fontSize: 40,
    border: "2px solid black"  
  };
  return (
    <div style={style}>
      Hello World!
    </div> 
  );
}

We define an object style with CSS properties and values. After that, we pass the object to the style attribute of the element.

Some benefits of inline styles

  • Simple and straightforward
  • CSS is bundled with your components
  • Easy to dynamically generate styles from JavaScript

Some drawbacks

  • CSS is embedded in your JavaScript, separating your concerns
  • CSS code can be repetitive and clutter your components
  • Hard to reuse styles across components

Overall, inline styles are best for simple, one-off styles. For more complex styles, I recommend

  • Using a separate CSS file and importing it
  • Using a CSS-in-JS library like styled-components
  • Using a CSS framework like Bootstrap or Material UI

Those options give you

  • Reusable styles
  • A cleaner separation of concerns
  • The ability to name your CSS classes

Get 100% Hike!

Master Most in Demand Skills Now!

Using Styled-Components

The popular library, styled-components, enables you to write CSS in your JavaScript code. It provides various features, such as theming, prop-based React Js styling, and server-side rendering. By using styled-components, you can enhance the readability, maintainability, and reusability of your code. However, it necessitates a learning curve and may not be suitable for small projects.

Pros

  • Easier to reuse styles. You can create reusable style components
  • No class names. Styles are applied using component names
  • Supports CSS nesting, variables, and media queries
  • Easy prop-based styling. Pass props to style components to dynamically style them
  • Automatic vendor prefixing
  • Theming support. You can create theme objects and pass them to style components.

Usage

import styled from 'styled-components';
const Button = styled.button`
  background: palevioletred;
  color: white;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;
function ButtonComponent() {
  return <Button>Click me!</Button>
}

We import styled and use it to create a style component Button from an HTML tag button.

Cons

  • Steeper learning curve than regular CSS
  • May increase bundle size
  • More complex setup for server-side rendering

Overall, styled-components is a great option if

  • You want to colocate styles with components
  • You want prop-based styling
  • You want to reuse styles

But for simple projects, regular CSS may be enough. styled-components really shine for medium to large projects.

CSS Modules to Style React Components

React Js CSS in Js Modules is a technique that allows you to write CSS in a modular way by creating a unique class name for each CSS module. This approach can solve the naming conflicts and specificity issues of CSS classes and allows you to use standard CSS syntax. However, it requires additional setup and configuration, and it may not be as flexible as other approaches.

Pros

  • Class names are scoped by default. Class names are prefixed with the component name to avoid conflicts. For example:
/* Button.module.css */ 
.button {..}
// Button.js
import styles from './Button.module.css';
<button className={styles.button}>...</button>

Compiles to

<button class="Button__button">
  • Uses standard CSS syntax. Easier learning curve than CSS-in-JS libraries
  • CSS is bundled per component

Setup

  • You need a bundler like webpack configured to enable CSS Modules
  • Import your CSS file and use it as a JavaScript module
import styles from './styles.module.css';
  • Class names are exported as object properties:
{ button: 'Button__button'} 

Cons

  • Requires additional webpack configuration
  • Less flexible than CSS-in-JS libraries
  • No nesting, variables, etc. Just plain CSS, So in summary, CSS Modules
  • Solves namespacing issues by scoping class names
  • Uses a familiar CSS syntax
  • But requires some webpack configuration
  • And is less flexible than CSS-in-JS options

Styling with Tailwind CSS

Styling with Tailwind CSS

Tailwind CSS is a utility-first CSS framework that provides a set of pre-defined CSS classes that you can use to style your components. It offers a range of features, such as responsive design, theming, and customization. Tailwind CSS can make your code more concise, maintainable, and easy to read. However, it can be overwhelming for beginners, and may not be suitable for complex designs.

Pros

  • Easy to style elements quickly. Tailwind provides many utility classes for common styles.

For example

<button class="px-4 py-2 text-white bg-blue-500 rounded">Button</button>
  • No class name conflicts. Class names are descriptive
  • Easy responsive design. It provides responsive utility classes
  • It allows high customization with the ability to add your own utility classes
  • Good for prototyping and simple designs

Usage

<link href="tailwind.css" rel="stylesheet">
  • Add Tailwind utility classes to elements
<button class="px-4 py-2 text-white bg-blue-500 rounded">Button</button>
  • Write your own utility classes in tailwind.config.js.

Cons

  • Steeper learning curve than regular CSS
  • May result in verbose class names
  • Not ideal for complex designs
  • Large file size

But for complex designs, regular CSS or CSS-in-JS may be better options.

Sass and CSS Style Sheets in React

Importing CSS/Sass stylesheets into React components is a good practice for scaling the React Js styling of larger React apps, but it requires some initial setup and may be overkill for simple projects.

  • Sass is a CSS preprocessor that enables you to use variables, mixins, and functions in your CSS. So, Sass files are compiled into CSS which can then be imported into your React components.
  • Plain CSS style sheets can also be imported into your React components and used to style them.
  • Using stylesheets can make your CSS modular, reusable and maintainable by splitting it across multiple files instead of having one large CSS file.
  • However, to actually import CSS/Sass files in React, you need to set up a build tool like webpack. This tool can import the Sass/CSS files and bundle them along with your JavaScript.
  • For small projects, setting up webpack and importing external style sheets may add unnecessary complexity. In such cases, it’s simpler to just write inline CSS styles for components.
  • As your application grows, transitioning to external stylesheets imported into each component can make the CSS easier to manage and maintain across multiple components.

What is the Best Way to Style in React?

For simple components or prototypes, inline styles are the easiest and quickest to implement. They keep the React Js styling directly in the JSX. However, as your app grows, inline styles can become hard to maintain and reuse across the components.

External stylesheets per component can make styling more scalable and maintainable in larger React apps. CSS modules are an effective solution, as they scope styles to individual components and reduce the risk of style conflicts. Using preprocessors like Sass or Less can also make your styles more reusable with features like variables, mixins, and nesting.

In a React app, you can combine different styles approaches

  • Use inline styles for small, simple components Implement CSS modules for complex, reusable components
  • Have global stylesheets for layout and shared styles

To import external stylesheets in React, you’ll need a build tool like webpack that can bundle the styles with your JavaScript.

The best React Js styling approach depends on your specific requirements, team experience and preferences. As a general rule, it’s recommended to start simple with inline styles and then gradually move to external stylesheets as your app, and number of components grow. You should experiment with different solutions, and choose what works best for you.

Conclusion

In conclusion, React Js styling is an essential part of creating a visually appealing and engaging user interface in React. There are several ways to add style to your components, including inline styles, styled components, CSS Modules, Tailwind CSS, Sass, and CSS style sheets.  By choosing the right approach,and following best practices, you can create a visually appealing and maintainable React application.

Course Schedule

Name Date Details
Web Development Courses 07 Dec 2024(Sat-Sun) Weekend Batch View Details
14 Dec 2024(Sat-Sun) Weekend Batch
21 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.