3 Ways to Style React Components
Styling — is one of the elements in the front-end triada that every web developer must know: HTML/CSS/JS 🤔. On the other hand, there is a large group of web developers who don't like CSS. They prefer to use some helpers and libraries and basically try very hard to avoid writing this mysterious styling language. And we shouldn't judge these people, especially when it's related to React, because it's the essence of JSX.
Anyway, this post is for: lovers ❤️ and haters 😠. We will review 3 ways to turn the process of styling react components into a pleasant journey. You can choose the styling options that give you more or less control over your use case.
1. Use CSS modules to fully control the style of React components
Yes, you can completely ignore these libraries and use directly CSS/SCSS/SASS
as if we don't have any JSX. This feature react-scripts@2.0.0
is available starting from . Basically, everything can be used as you wish. [name].module.css
Create a stylesheet using the following syntax .
Text.module.css
.success { background-color: green; }
And simply import the component
import React from 'react';
import styles from './Text.module.css'; // 将 css 模块样式表作为样式导入
const Text = () => {
return <div className={styles['success']}>Successful message</div>;
}
style['class-name']
This format is preferred style.className
over to keep our class names close to standard kebab case instead of ugly camel case.
It will automatically scope the styles for us using [filename]_[classname]_[hash]
the format, and the end result will look like this in the browser:
<div class="Text_success_sdfg43l">Successful message</div>
We can also use preprocessor stylesheets like SCSS and SASS, just install npm install scss
or npm install sass
.
This approach gives us complete freedom in how we use CSS and eliminates the need to learn new syntax or libraries.
2. Use Chakra UI styling without CSS
These are my top 2 options, perfect for side projects and small to medium web applications. This year, tailwind has become very popular, and many web developers have found it to be the perfect solution for styling components without writing a single line of CSS. Its downside is that we need to look up the library a lot in the beginning until we get used to it. Another problem is that there will be a bunch of classes inside the component, which will bloat your React component and force you to duplicate the classes.
Chakra UI is similar to this, but in addition to styles, we also get UI components. It has everything you need to build any complex layout. It is also flexible enough if you need more sophisticated customization. The difference with tailwind is that in Charka UI, we will mainly pass styles through props instead of writing a list of classes, and it looks more natural for React applications to use props.
First, we need to install the dependencies:
$ npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
Set the provider to the root of your application:
function App() {
return (<ChakraProvider>
<TheRestOfYourApplication />
</ChakraProvider>)
}
Now you can start:
<Text fontSize='6xl'>Your 6xl size text</Text>
If you don't need subtle styling and want to prototype your app quickly, this solution can quickly meet your needs. I like to use it in most of my projects.
3. The King of React Styles — styled-components
Not my favorite, but one of the most popular React styling libraries is Styled Components. It is used by many well-known companies. The reason I don't like it is that you need to create a new component every time you want to apply some simple styles. Maybe this makes sense in the normal world, we need to add a class, but here we will have a separate component. If you want to build your own UI component library, this can be a good solution. styled-components
A cool feature of is that you can set style conditions through props, and it is customizable.
Start by installing the dependencies:
$ npm install --save styled-components
Now we are ready to create our first styled-component:
const Container = styled.div`
text-align: center;
`
We can then use it as a component:
<Container>Your text</Container>
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap