5 ways to style React apps
We will talk about some ways to apply styles to React apps.
Styling an application is one the most critical areas of web development, both user that consumes the system and developers that have to work with the styling code.
We must learn all available ways to style React applications to create high-performance and maintainable apps.
Learn 5 essential styling ways to stand out as a front-end developer
The fundamental ways to apply styles on a React application:
Inline styles
CSS Modules
Styled-components
SASS & CSS Stylesheets
Tailwind CSS
We are going to explain each one. Let's dive in.
1. Inline styles
We can add inline styles in JSX. We have to keep in mind to add styles like an object in the following way:
We must add an object between double curly braces like in the above image.
Pros:
You can quickly prototype your interface.
Cons:
For large projects, the code can quickly get messy.
We can’t apply styles for responsive designs.
2. CSS Modules
We can create a file ending with .module.css. It is a CSS file which we apply with local scope to the React components.
Pros:
You can avoid bugs with override styles like happen with global CSS files.
Cons:
This approach can be confusing for beginners.
3. Styled-components
We need to install an npm package in the project. We can create React components with integrated style and add JavaScript logic inside them.
Pros:
Local scope in each component.
Very powerful the possibility to add logic inside of them.
Cons:
You need to install an extra package.
We get an extra overload on the web that can impact performance.
4. SASS & CSS Stylesheets
We can follow the standard approach of having SASS/CSS stylesheets. It is crucial for large projects following the BEM convention, and I strongly recommend it.
Pros:
We can have a robust architecture supported by a strong community, very tested in large production projects.
Cons:
Steep learning curve.
5. Tailwind CSS
It is a library with utility classes allowing us to create interfaces quickly.
Pros:
Highly customizable.
Easy and fast development.
Avoid bugs due to overriding styles.
Cons:
Moderate learning curve for use and best practices.
Here, I share 3 helpful resources that also talk about this topic. I strongly recommend them:
https://blog.logrocket.com/styling-react-5-ways-style-react-apps/#styling-tailwind-css
https://geekflare.com/style-react-using-css/
https://www.freecodecamp.org/news/style-react-apps-with-css/
Conclusion
All ways have their pros and cons. It is crucial to study and analyze the options and see if we comply with the app's needs by using them.
Also, remember we can apply 2 or 3 ways together, such as inline styles in some instances and CSS Modules or CSS stylesheets.
Recommend Tailwind CSS because it's easy once you get used to it. Moreover, it is very readable, efficient and customizable. It fits great in many projects.
See you next Saturday!
Keep up the great work! :)