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.
Setting up your React application
Before applying styles in React, you need to properly set up your development environment. The most common and efficient way to start is with Create React App (CRA), which handles all the tooling and configuration out of the box.
Steps to Step up a React Project:
1. Create a React App using Create React App (CRA)
npx create-react-app my-app
cd my-app
npm start
2. Add your styles to the React App
Once your project is set up, we can style our components using several methods:
2.1. Import a CSS file globally
import ‘./App.css’;
2.2. Use inline styles directly in JSX
const divStyle = {
color: 'blue',
padding: '10px'
};
<div style = {divStyle}>Hello World</div>
2.3. Apply class names from a stylesheet
<div className="header">
<h1>Welcome</h1>
</div>
2.4. Installing a UI framework (optional)
You can enhance styling by installing libraries like Bootstrap or Material UI
npm install bootstrap
// Then import in your JS file
import 'bootstrap/dist/css/bootstrap.min.css'
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.
Different Ways to Add Styles in React
React allows us to style components in a variety of ways. Here are some of the most popular techniques/methods for accomplishing the same.
1. Styling React Components with Inline Styling
Inline React Js styling is the simplest way to add style to your React components. It involves defining style objects in JavaScript and passing them to the style attribute of JSX elements. While inline styling is straightforward, it can make your code harder to read if you have a lot of CSS properties.
1.1. Example Usage of Inline Styling
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.
1.2. Advantages of Inline Styles
- Easy to dynamically generate styles from JavaScript
- Simple and straightforward
- CSS is bundled with your components
1.3. Disadvantages of using Inline Styles
- Hard to reuse styles across components
- CSS is embedded in your JavaScript, separating your concerns
- CSS code can be repetitive and clutter your components
Get 100% Hike!
Master Most in Demand Skills Now!
2. Using Styled-Components
Styled-components is one of the most popular CSS-in-JS libraries that, enables you to write CSS in your JavaScript code. It provides various features, such as theming, prop-based ReactJS 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.
2.1. Example Usage for Styled Components
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 define an object style with CSS properties and values. After that, we pass the object to the style attribute of the element.
2.2. Advantages of Styled-Components
- Theming support. You can create theme objects and pass them to style components.
- 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
2.3. Disadvantages of using Inline Styles
- Steeper learning curve than regular CSS
- May increase bundle size
- More complex setup for server-side rendering
3. CSS Modules to Style React Components
CSS Modules allow you to write traditional CSS while scoping styles to individual components. This approach can solve the naming conflicts and specificity issues of CSS classes by generating unique class names at build time 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.
3.1. Example Usage of CSS Modules
.button {
background-color: teal;
color: white;
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
}
import styles from './Button.module.css';
function Button() {
return <button className={styles.button}>Click Me</button>;
}
This compiles to a scoped class like Button_button__1A2B3
3.2. Advantages of CSS Modules
- Tooling support that helps to interact seamlessly with Create React App and Webpack.
- Class names are scoped by default. Class names are prefixed with the component name to avoid conflicts. For example:
- Scoped styles prevent class name clashes.
- Standard CSS syntax is familiar and simple to use.
- Works nicely in a component-based architecture.
3.3. Disadvantages of CSS Modules
- And is less flexible than CSS-in-JS options
- 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
4. 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. It promotes a rapid and consistent development workflow without writing custom CSS. However, it can be overwhelming for beginners, and may not be suitable for complex designs.
- 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.
4.1. Example Usage of Tailwind CSS
function Button() {
return (
<button className="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
Click Me
</button>
);
}
This button is styled entirely using utility classes, without any external stylesheet.
4.2. Advantages of Tailwind CSS
- Easy to style elements quickly. Tailwind provides many utility classes for common styles.
- Rapid styling is useful for applying styles directly to utility classes.
- Create responsive and mobile-first UIs with built-in responsive utilities (sm:, md:, lg:, etc.).
- Consistent design aids in enforcing a design system through centralized configuration.
- Tailwind.config.js allows you to customize space, colors, and other settings.
- There are no name issues because the classes are descriptive and explicit.
4.3. Limitations of Tailwind CSS
- There are large bundle sizes; if not properly purged, unnecessary styles might clutter your CSS
- Learning Tailwind requires time to master utility classes and best practices.
- Verbose JSX class strings can grow large and difficult to handle.
But for complex designs, regular CSS or CSS-in-JS may be better options.
5. 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. These styles are written in external .css or .scss files and imported into your components.
- 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.
5.1. Example Usage for CSS Stylesheets
You can define styles in a .css file and apply them via className.
5.1.1. CSS Stylesheets
/* styles.css */
.title {
font-size: 2rem;
color: navy;
}
5.1.2. JSX file
import './styles.css';
function Title() {
return <h1 className="title">Hello World</h1>;
}
5.2. Example Usage for Sass (SCSS)
Sass is a CSS preprocessor that adds powerful features like variables, nesting, mixins, and functions.
5.2.1. Style.css
/* styles.scss */
$primary-color: teal;
.button {
padding: 1rem;
color: white;
background-color: $primary-color;
&:hover {
background-color: darken($primary-color, 10%);
}
}
5.2.2. JSX file
import './styles.scss';
function Button() {
return <button className="button">Click Me</button>;
}
5.3. Advantages of using Sass and CSS Style Sheets
- Scalable structure makes it easier to spread CSS across numerous files.
- Using Sass and CSS Style Sheets, we can keep JSX and styling separated.
- Many developers are already familiar with classic CSS.
5.4. Limitation of using Sass and CSS Style Sheets
- In comparison to CSS-in-JS, it is more difficult to modify styles dynamically here.
- We need bundler support (like webpack) to compile Sass.
- Global scope: Unless CSS Modules are used, styles may clash.
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.