By creating a website that is more accessible to users of disabilities you make it so that all...
How should you handle styling in your React applications?
When building your React applications there are multiple ways you can style your components but which one should you use? There isn’t a single correct way to style your components, in the end, it usually comes down to use case and personal preferences but it is good to know the different options you have when handling styling in React. So here's an intro to some of the basic ways you can style your application.
Inline CSS:
Inline styling is the most basic form of styling that can be used. We create an object with our styling attributes and apply it directly to the element. This is the easiest way to do styling but does not offer anything in terms of reusability as each style object must be manually updated one at a time. Readability is also an issue since, as style objects grow and have more attributes, being able to tell what each styling does at a glance becomes harder. One benefit of inline styling is that there are no dependencies needed to use inline styling.
CSS Modules:
CSS Modules is a library that lets us use CSS files that are only scoped locally by default. These ensure that no styling is globally applied, giving you more power to only apply styling to certain components or files. Working with regular CSS is also a benefit as we don't have to spend time adapting code (kebab case to camel case). Also styling features like ‘composes’ lets us extend different styling to different selectors. CSS modules are included when building an app through the “create-react-app” tool but can also be added to any project with the use of Webpack and some loaders.
Styled-Components:
Styled components is a library that uses template literals to style your components. So instead of mapping styles to different components, they are attached to each other and act as a component themselves. This lends to more readability as you can now the component name now describes the component. Styled components are also written in CSS thanks to template literals so no time adapting code.
There are other popular ways to style your application such as Sass which is a feature-rich styling library that lets you use variables, functions, and nesting within your application. Whichever one you choose it's important to consider the size of your project and which method gives you the best benefits without too much overhead.
Blog comments