CSS and React Components
Explore how to bundle CSS with React components using the styled-components library. Understand the benefits of defining CSS inside component files, managing styles more effectively, and preventing style bugs. Learn the installation and usage process for styled-components in a Rails context with TypeScript, and see how to create styled React components to improve styling clarity and modularity.
Introduction
Where Stimulus encourages using the markup we are already writing, therefore keeping CSS in its own separate files, React encourages thinking about CSS and code together. Once we get in the habit of thinking of our page as made up of a number of different React components, it’s a small step to imagine those components containing their own CSS for features that are specific to that component.
Including CSS with React code is so common that there are many libraries that can handle this. We’re going to talk about one of these libraries that has an interesting way to insert CSS into our React code: the styled-components library.