How To Style And Write CSS In React

Adarsh M

Posted On: August 12, 2022

view count36132 Views

Read time21 Min Read

React is an extensively preferred frontend UI library used in nearly 50 million projects every month. Backed by Facebook, React has had its dominance in the web development space for over nine years and has several notable customers (ranging from startups to Fortune 500 companies).
Simplicity and flexibility are the two primary reasons that contribute to React’s growing popularity.

Front-end defines the success of any online business since it brings considerable improvement in web performance. It takes only 0.05 seconds for an average user to have an opinion of a business/product by looking at their website. Undoubtedly, it is necessary to have a good UI layout, design, and overall experience on the web.

As per npmjs, React garners close to 15,353,836 weekly downloads, whereas VueJS, its nearest competitor, has 3,334,067 weekly downloads. Also, Angular has only 2,918,034 weekly downloads.

React-garners

Source

As a React developer, you will usually be working on styling your React application. Being a freelancer, I have made that mistake, and I still regret it! I do not want any front-end developer to commit the same mistakes.

In this detailed tutorial on CSS in React, we will walk you through the various methodologies through which you can style the React application with CSS.

So, let’s get started!

Getting started with application development using React

To create a React application, the first thing you need is NodeJS, a runtime for JavaScript.

  1. You can download the latest stable version of NodeJS from their official website and install it like a regular application.
  2. Once NodeJS is installed, run the below command on the terminal to know the version of NodeJS:
  3. Terminal-command-NodeJS-1 (1) (1) (1) (1) (2)

  4. After installing NodeJS, run the following command on the terminal.
  5. It will create a React app on which we will work during this blog on CSS in React.

    React app

    React application

  6. Now that you are ready with the React application, the next step is editing the App.js file. At any moment, you can see the results on the browser by running the following command on the terminal:
  7. Shown below is the folder structure, which is pretty self-explanatory!

    React folder structure

    • node_modules (Folder): Constitutes the dependencies for React. It is a huge folder with over 1500 subfolders and 15000 files. The overall size is close to 170 MB.
    • Public (Folder): This is where index.html is located. It is the most important folder since the React framework will insert the corresponding React code in index.html. It is a good practice to store assets like images, videos, and logos in the Public folder.
    • Public folder react

    • src: This is where the core React logic resides. You could start editing the React application by making changes to App.js.
    • package.json: When working on JavaScript projects, package.json is one of the most important files. It has a list of all the dependencies that we would require in the project.

    FileName – package. json

    package.json is the heart of the NodeJS file. It contains all the important pieces of information about the project. This JSON file consists of the following:

    • Project name.
    • Project dependencies.
    • Project version.
    • Project description.
    • Project License.
    • Versions of different packages used in the project.
    • Scripts to run the file, and more.
  8. When you install a new package or dependency via npm install, the node package manager will install the latest stable version. Run the following command on the terminal if you want to install a specific package version:
  9. The status of the React application can be monitored by visiting http://localhost:3000 in the web browser. The default port for React is 3000. Under certain circumstances (e.g., port already in use), you might want to change the port.
  10. You can achieve this by changing the start script in package.json:

    Script in package.json

As a result of all this, the website will appear as below:

React website

Introduction to CSS

You may have already read a lot about CSS, which stands for Cascading Style Sheets. Without styling, your website would appear like a pale, dull B&W movie that none of us would enjoy watching in today’s times 🙂

A good design can make your business/product look professional and can transform interactions into relationships. It is one of the major drivers of growth and retention. See how an ultimate mobile experience can drive 73% of e-commerce sales.

Can you just imagine your favorite e-commerce shop without any CSS?

Without CSS:

E-commerec without CSS

With CSS:

With CSS

The possibilities with CSS are endless, and with your design skills, you can create wonders for your website – the ideal vehicle to drive experience and sales. Before proceeding to the next section of this CSS in React tutorial, check our CSS cheat sheet tutorial.

Advantages of CSS

So far, we have touched upon the fundamental aspects of CSS. Let’s deep dive into some of the integral benefits offered by CSS:

So far, we have touched upon the fundamental aspects of CSS. Let’s deep dive into some of the integral benefits offered by CSS:

  • With CSS, you can make a good and better visual appearance for text and images on your website.
  • You can manage the website’s overall layout and flow without compromising even a single bit on the friendliness and usability of the website.
  • By using CSS, you can apply consistent styling across multiple devices to improve the user experience. It ensures that your website is responsive and displays similar behavior on different devices.

Now we have an overall idea about why CSS and the advantages of using CSS, it’s time we look into how to leverage CSS skills in React applications.

Introduction to React

React is one of the most used front-end libraries that can be used to create simple landing pages as well as complex enterprise websites.

React (a component-based library) makes it easy to create UI components for every separate section. The website under development makes separate reusable components for each section like header, footer, sidebar, and more.

Community is one of the strong points of the React framework. Having said that, React is not an all-in-one solution; for instance – there is no in-built page routing feature in React.

There are thousands of libraries to support the React ecosystem, like react-router-dom for page routing, react-redux for state management, and more.

React ecosystem

Source

React, with its huge ecosystem, makes it a wholesome solution for web application development.

How to style and write CSS in React?

Styling is one of the most important aspects of the React application. Having worked on several React applications, I can vouch that most of the time goes into designing the application.

There are five distinct ways in which you can style and write CSS in React:

  • Inline styles in React
  • Reusable variables
  • Using external StyleSheet
  • CSS Modules
  • CSS-in-JS

Let’s deep dive into each of these in more detail:

Inline Styles in React

Inline CSS is the widely preferred but less recommended way to style your website. This is not just in the case of React. Even with raw HTML, writing inline CSS makes it difficult to edit in the future.

Inline styling is the best way to try different CSS properties. One key point to remember is that inline styles have got more priority, and they will overwrite any other styles given to them in any manner.

Writing Inline CSS in React and plain HTML has a small difference. In HTML, you will write your style using the style attribute followed by = and then CSS properties enclosed by double quotes or single quotes. In React, we will use double curly braces {{ }} instead of quotes “ ”.

HTML

React

When to use Inline Styling?

Inline styling is ideal when we are creating a simple website and when you are the only one working on that project. Simply put, inline styling is an absolute no-no for projects involving large distributed teams. Inline CSS in React is preferred when you are testing a particular style.

In short, inline CSS is best suited for learners but not for implementing real-world web projects.

Here is why you should not use inline CSS in React:

  • Inline CSS cannot be reused, i.e., you must write the same CSS code repeatedly for the same styles.
  • Inline CSS does not provide browser cache advantages.
  • Some vital CSS properties like pseudo-codes, pseudo-classes, media queries, etc., are not allowed to be used in inline styles.

Writing Inline CSS in React is not wrong, but adding CSS rules to every HTML element is time-consuming and makes your HTML structure messy.

Inline CSS Example

FileName – App.jsx

Output:

Inline CSS

CodeSandbox

Reusable variables

Replicating the same code is not a good idea in the programming world. That’s the same case in CSS too.

Here, you could use object variables instead of writing the same code repeatedly for a similar UI component. All you have to do is create the object variable to store a particular style and use the variable names, not the style itself. This variable now has predefined styles, and you can use it as often as you want.

The example below shows that the same divStyles is used for two different div elements.

When adding style to a website, one of the major goals should be to use the same CSS class multiple times for similar elements. While implementing CSS in React, we use the object variables to achieve multiple styling in one go.

The advantage here is that we will reduce many redundant lines of code, thereby improving the code’s maintainability, reliability, and readability.

Output:

Output

CodeSandbox

From the syntax, you might have noticed that inline CSS in React is still being used, owing to which we cannot use pseudo-classes, pseudo-elements, etc.

One thing to note is that if there are two or more kinds of styling (Inline + External) to the same element, Inline CSS in React will have a higher preference over the other ones.

External CSS

This is one of the preferred ways of writing CSS in React. Instead of writing the CSS code inside HTML (i.e., Inline CSS), we separate the CSS part into a separate file which is simply imported into the React component.

The advantage of external stylesheets is that we get complete control over the CSS properties (e.g., pseudo-selectors), which is impossible with inline CSS in React.

Here all we have to do is create a filename with a .css extension and import it into the React file.

React file

Now we can give className and id to point which styles should point to which element. It is important to note that the class attribute is used in HTML, whereas className is used in React.

  • className: Used to style two or more elements with the same CSS in React. Different elements can have the same className
  • Id: Used to style a particular element. Different elements cannot have the same IDs, id’s are unique.

One thing that we should focus on is the naming convention for classes and IDs. There is a good chance that if we are writing complex web UI, we may unknowingly create multiple className with the same name.

A naming convention called BEM is the answer to the problem listed above!

Naming Convention – BEM

BEM stands for Block Element Modifier. Using proper naming conventions will prepare you for the changes in the design of the website

  • Block
    Block Refers to a standalone entity. Think of Block as a container that has several children.
  • Bem Block

  • Element
    Parts of a block that have no standalone meaning. Any element is semantically tied to its block.
  • BEM Element

  • Modifier
    They are the flags on blocks or elements. Use them to change appearance, behavior, or state.
  • BEM- Modifier

BEM is one of the most commonly used naming conventions. You can name it according to your logic.

CSS Modules

A CSS Module is a CSS file with a .module.css extension in which all class names and animation names are scoped locally by default. There is no global CSS. CSS Modules let you write styles in CSS files but consume them as JavaScript objects for additional processing and safety.

One huge advantage of the CSS modules is that you would not witness any className conflicts. The CSS properties we target are converted into unique class names during compilation.

CSS Modules In React Application

While working with CSS in React, you can use CSS Modules by creating a [name].module.css file and import it into the specific React Component file.

FileName – App.js

App.module.CSS

Output:

CSS-Modules-output

CodeSandbox

Here, you can see we have our App.js file and App.module.css file. Though this seems normal, the fun starts when you check it in the browser.

CSS Modules in browser

As you can see, we didn’t specify a class name in the CSS. Here our class name is .._src_App_module__block which is further transformed into a Unique Identifier. This will remove any chances of name collision in the React App.
CSS Modules are a great way to make CSS have local scope; everything is done during the compilation. Deciding good class names will be a thing of the past with CSS modules 🙂

CSS-in-JS

JSX would sound familiar in case you already know React. JSX looks like HTML, but it is not. Unlike HTML, it comes with the full power of JavaScript. Along similar lines, CSS in JS comes with some extra features to CSS.

CSS-in-JS is one of the approaches to write CSS, which tries to eliminate some of the blockers with plain CSS, such as scoping, portability, and dynamic functionality.

A well-designed CSS-in-JS library will group all its CSS properties and the dependencies associated with it. All style logic is now separate and reusable.

The common features of all CSS-in-JS libraries are:

  • Scoped CSS – You may have noticed that there will be unique names for classes when you use this kind of library. This makes it easy to handle name collisions. Since there is no concept of global styles, it does not accidentally impact any unintended element.
  • No inline styles – The most popular CSS-in-JS libraries are not using inline styles, due to which there is full control over all the CSS properties.
  • Logic separation – The layout and design/UI logic are separated, making the code easier to read and format.

Let’s now look into some popular CSS-in-JS libraries:

Styled JSX

Styled JSX is a very small library built and maintained by the NextJS team. It allows you to write encapsulated and scoped CSS in React to style your component(s).

  1. Run the below-mentioned command to install styled JSX:
  2. Post that, add styled-jsx/babel to plugins in your babel configuration:
  3. Now you can start using styled jsx in your React application.

Look at an example where styled jsx is used for styling the React application:

Output:

Styled JSX Output

CodeSandbox

styled-component

Styled-components is a library built for React and React Native. It allows you to use component-level styles in your application. What this means is that you can create styles for particular UI components. styled-components is a mixture of JavaScript and CSS i.e. CSS-in-JS

Let’s now look at start working with styled-components:

FileName : App.js

Output:

styled-component output

CodeSandbox

These two are the most common CSS-in-JS libraries. Several other CSS-in-JS libraries like JSS, Emotion, Styletron, etc., allow you to write component-level CSS using JavaScript.

Top CSS Frameworks

Styling is not just restricted to writing raw CSS. You can also use various frontend CSS libraries like Tailwind CSS, Bulma, Ant Design, etc. Using the best CSS frameworks and libraries is now quite popular since it is developer friendly and reduces the development time by a huge margin.

Some of the best CSS frameworks are:

Tailwind CSS

Tailwind CSS

Tailwind CSS is one of the most extensively-used CSS frameworks. It is a utility-first framework with nearly 13 million monthly downloads. It gives you flexibility and freedom to choose your website’s design.

Tailwind CSS has several advantages, namely that it can be customized to meet individual needs. Tailwind CSS comes with its default configuration, but you can override those. Tailwind’s utilities and components are easily customizable.

Tailwind uses a mobile-first breakpoint system which means you can specify prefixed utilities like sm: md: lg: that only take effect at the specific breakpoint and above.

FileName – App.js

Output:

Tailwind CSS output

CodeSandbox

Even though we are using Inline styles here, it is pretty neat and easy to manage. Tailwind CSS gives us class names for a particular style. When using Tailwind CSS, everything is under your ( read developer’s) control. You can also use pseudo-classes and pseudo-selectors with Tailwind CSS.

React Bootstrap

React Bootstrap

React-Bootstrap replaces Bootstrap JavaScript. React-Bootstrap is one of the best React component libraries that provides Bootstrap components as React components. Each component has been built from scratch as a true React component.

It is one of the best solutions and the most used UI library for React. More than 1.3 million weekly downloads are there for React-Bootstrap.

For JavaScript web applications, React dominates, while Bootstrap dominates CSS web frameworks, powering millions of websites worldwide.

React Bootstrap includes several components you can use without having to create them from scratch, such as navbars, buttons, forms, cards, etc.

FileName – App.js

Output:

React Bootstrap Output

CodeSandbox

Material UI

Material UI

Instead of you building a new UI component, Material UI creates an individual component that can be tweaked to achieve the desired UI output.

A Material-UI component only injects the styles it needs to display and is self-supporting. They don’t rely on any global style-sheets concept. Material UI can also be used with other frameworks like Angular and vue.js to help you ship the new UI features faster and make them responsive and adaptive.

In Material UI, user interfaces are based on high-quality digital experiences that provide a high-quality digital experience while developing front-end graphics. It is based on Google’s Material Design.

With over 79,900 plus stars on GitHub, Material UI is one of the top User Interface libraries for React.

FileName – App.tsx

Output:

Material UI output

CodeSandbox

There are many more UI components and CSS libraries that work well with React.

As per my experience working with global clients, I can confidently mention that there is no single best solution. The choice depends on the project and the developer’s ease with the framework. You have to decide how to style and write CSS in React!!

Using LT Browser to test CSS in React

To test our project, we should use tools that make it easier to see what the pages look like and test accessibility and usability of the website or web app.

LambdaTest’s cloud-based cross browser testing helps you deliver hassle-free, user-friendly, and responsive web experiences across all browsers, operating systems, and real devices. It enables you to perform web testing on an online browser farm of 3000+ real browsers and operating systems.

You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated browser testing, Selenium automation, Cypress automation, CI/CD, and more.

LambdaTest provides a comprehensive solution with its mobile-friendly testing tool to perform responsive testing of your website. LT Browser comes loaded with 50+ pre-installed mobile-friendly viewports, and advanced developer tools for testing react application’s responsiveness. Learn to implement react testing with this react end to end testing guide.

Wrapping It Up!

Congratulations on reaching this far! You’re a fantastic reader!!
In this detailed blog on CSS in React, we looked at how we can make our application look beautiful and pretty. Not only did we experiment with styling CSS in React, but we also discussed various best practices to implement.

Now you know how to style your application in the most effective & efficient way.

Happy Styling!

Frequently Asked Questions (FAQs)

Is CSS used in React?

The short answer is: yes, CSS is used in React. And that’s kind of a loaded question because CSS isn’t just “used” in React—it’s baked into it.
There are two ways to use CSS with React: firstly, you can use CSS in your component stylesheets, and secondly, you can use it to style the built-in component types.

Which CSS is best for React?

With the rising popularity of React, it’s natural to want to use a CSS-in-JS library with it. At a high level, there are two main options: one is inline styles, while the other option is a framework like styled components or emotion.

How to add background images in ReactJS CSS?

To add a background image in React JS using CSS, you can set the background Image property in the CSS file or inline styles. Specify the URL of the image as the value for the backgroundImage property. This will set the background image for the desired component or HTML element.

What is CSS in React?

CSS in React is a way to style React applications or components. It involves using the style attribute to add dynamically computed styles at render time, allowing for flexible and customizable visual design.

Is CSS part of React?

Yes, CSS is a fundamental part of React. It is used to style React applications and components, allowing for the visual customization and layout of the user interface.

How much CSS is needed for React?

Fundamental knowledge of CSS is necessary to appropriately style React components. You must be familiar with CSS syntax, selectors, and the React framework’s style implementation. If there are styling components in your React project that won’t change regularly, you can build and import CSS files.

How to apply CSS Bootstrap in React?

To apply CSS Bootstrap in React:

  1. Install react-bootstrap package.
  2. Import Bootstrap CSS file.
  3. Import desired Bootstrap components.
  4. Use the components in your React code.
Author Profile Author Profile Author Profile

Author’s Profile

Adarsh M

Adarsh is a full-stack JavaScript developer based out of India. He loves creating meaningful technical content on Twitter, where he connects with like-minded individuals and developer communities. He shares his knowledge on Twitter through insightful threads!

Blogs: 9



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free