Introduction to Using Styled Components

In the React world, everyone has gotten used to styling their components by passing a className prop to them, referencing the CSS classes defined in some stylesheet. As you know, CSS classes encapsulate the styles needed for pages and page components, centralize them for easier maintenance and use, and are meant to ensure a consistent visual experience throughout a website. That’s great, but now with React, we're more and more thinking in smaller independent and reusable components, distinct from the rest – so why should their styles and classes contribute to bloating a global stylesheet?

The styled method lets you attach styles to HTML elements (styled.button) or to components (styled(Button)) using a template string.

As you can see, we’ve additionally derived a slightly different version, a “DangerButton”, from the “Button” component by overriding two styles. As a more dynamic approach, instead of providing a dedicated “DangerButton” component, we could have used a prop for switching the ”Button” styles:

Having access to a component’s props inside of style definitions makes this approach so tempting, especially with respect to theming (take a look at the ThemeProvider wrapper component, for example).

Styling Scrivito components

Scrivito includes several helper components for rendering CMS content like widgets, HTML markup, images, and a couple more. If Scrivito’s UI is active, these built-in components make content editable in “Edit” mode. Scrivito.ContentTag, for example, renders an attribute value of a CMS object or widget:

If you wish to directly change, for instance, the appearance of a widget, here’s how this can be done using the example of the “FactWidget” included in the Scrivito Example App. Originally, this widget’s component looks like this:

This technique lets us pass any number of further props, in this case just borderColor, to our styled component. And, if we wanted to, we could also override the styles passed in via className. For example, to change the font color set by the value and key classes, we’d replace it by adding color: green !important; to the ”BorderdFact” component’s styles.

Final words

Styled components are a great way to maintain and apply styles locally in your React components, which helps keeping stylesheets clear and focused on overall matters.

Scrivito page and widget components can be easily combined with styled components, whether you are integrating Scrivito with an existing React app, or just want to benefit from styled-components’ features such as dynamic styling or theming.