Back

Aug 29, 2022

Aug 29, 2022

Styling Components with React Themes

Learn how to implement styling components in your React projects with the styled-components library.

A person typing on a laptop.
A person typing on a laptop.
A person typing on a laptop.

Styling is a vital aspect of front-end web development. It helps to create a great user experience and gives a web application a clean layout. There are a ton of style libraries and frameworks out there, but in this article, we’ll be looking at how to style React web applications.

What is styled-components?

Styled-components is a library for styling React components. It lets you use CSS-in-JS by adding JavaScript logic to your CSS. This makes it simple to create dynamic styles for your React components and integrate your react component library.

Advantages of Styled-Components

  1. Easy to learn

  2. Prevents class name collisions with unique class names

  3. Dynamic and adaptive styles

  4. Component-level styling for easier debugging

  5. Server-side rendering support

  6. Sass style support

  7. Custom style theme support

  8. Simple theme setup

Getting Started with Styled-Components

This section will explore how to add the styled-components library to your React application, style React components, and add light and dark themes. First, create a React app and install the styled-components library by running one of the commands below:

<pre>yarn add styled-components</pre>

or

<pre>npm install --save styled-components</pre>

Once we install the library, we will start styling the application.

Styling a React App with Styled-Components

Styled-components lets you add styles to React components with the react inline stylestyled interface. You'll use tagged template literals to pass style rules to the component.

import styled from "styled-components";

<pre>import styled from "styled-components";

const [Component Name] = styled.[DOM Element]`
  [CSS Style Rules]
`;</pre>

The component name follows the React naming convention. Access the DOM element you want to style from the styled object and pass the style rules within template literals.

Styling a real-life project's nav will look similar to this code block:

<pre>function App(){
  return &lt;Nav /&gt; 
}

const Nav = styled.nav`
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  border-bottom: 1px solid #878787;
`;</pre>

The code block above creates a styled nav element. You can pass props or add JavaScript logic to styled components.

<pre>const MyComponent = styled.div`
    opacity: ${(props)=> props.show ? 1 : 0};
`;</pre>

In the code block, the opacity style value depends on the show prop. If show is true in MyComponents, the div's opacity is 1, else 0. Use createGlobalStyle for global styles that are not tied to a specific component.

<pre>import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
  [global style rules]
`;

function App(){
  return (
    &lt;div classname="app"&gt;
      &lt;GlobalStyle /&gt;
      &lt;Nav&gt;
       &lt;BrandText&gt;Theme With Styled-Components&lt;/BrandText&gt;
      &lt;/Nav&gt;
      ...
    &lt;/div&gt;
  );
}</pre>

The code block above creates a global styled component that we can use to style components outside its scope.

React Themes

Styled-components supports multiple themes for React apps; use ThemeProvider to provide the theme via a context API. To do so, pass a theme rule object as a value to its theme prop, access the theme rule in all styled-components using prop.theme, and set up a theme object in the theme folder.

<pre>const darktheme = {
  primary: "#00bcd4",
  secondary: "#f3f3f3",
  border: "#e0e0e0",
  text: "#fff",
  background: "#212121",
  indicator: "#FFCC00",
};

const lightTheme = {
  primary: "#003366",
  secondary: "#eee",
  border: "#878787",
  text: "#000",
  background: "#fff",
  indicator: "#ccc",
};

const defaultTheme = {
  fontSize: {
    xs: "12px",
    sm: "14px",
    md: "16px",
    lg: "18px",
  },
  borderRadius: {
    small: "5px",
    medium: "10px",
    large: "15px",
    circle: "50%",
  },
};

const theme = {
  dark: {
    color: darktheme,
    ...defaultTheme,
  },
  light: {
    color: lightTheme,
    ...defaultTheme,
  },
};

export default theme;</pre>

The theme object exported as the default in the code block above has two properties: dark and light. We’ll pass the proper property to the ThemeProvider component based on the selected theme. The following action will wrap the application with ThemeProvider:

<pre>import styled, { ThemeProvider } from "styled-components";
import theme from "./theme";

...
function App() {
  const [currentTheme, setCurrentTheme] = useState("light");
...

return (
  &lt;ThemeProvider theme={theme[currentTheme]}&gt;
  &lt;Nav&gt;
    &lt;BrandText&gt;Theme With Styled-Components&lt;/BrandText&gt;
    &lt;ToggleButton&gt;
    currentTheme={currentTheme}
    onClick={() => {
       if (currentTheme === "light") {
       setCurrentTheme("dark");
     } else {
       setCurrentTheme("light");
     }
    }}>
      &lt;span&gt;&lt;/span&gt;
    &lt;/ToggleButton&gt;
  &lt;/Nav&gt;
  ...
  &lt;/ThemeProvider&gt;
 );
}</pre>

From the code block above, we have the currentTheme state; this controls the theme rule to pass to ThemeProvider. The ToggleButton component allows us to toggle between light and dark themes.

Using Themes in Styled-Components

To use the theme rules in the style component, we will need to access the theme from the props object:

<pre>const Nav = styled.nav`
  background-color: ${({ theme }) => theme.color.background};
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  border-bottom: 1px solid ${({ theme }) => theme.color.border};
`;</pre>

In the code block above, we are destructuring the theme property from the props object. This will give us access to all of the theme rules. Using the code sample above, we have:

<pre>background-color: ${({ theme }) => theme.color.background};</pre>

This will apply the primary color from the current selected theme's theme rule.

A mostly blank webpage with styled-components.

Conclusion

This article explored how to add styled-components to your React application and create component-level styles. In addition, we looked at how to create light and dark themes for React applications using ThemeProvider. If you would like to look further into styled-components, check out the official documentation. You can also find the complete code for the project used in this article in my Github Repository or test the live version here: https://theme-sc.vercel.app/. Want to learn more? Check out this article about how to implement drag and drop in React.

Melvin Kosisochukwu.
Melvin Kosisochukwu.

Written by

Written by

Melvin Kosisochukwu

Melvin Kosisochukwu

SHARE

SHARE

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.

our newsletter

Sign up for The Pieces Post

Check out our monthly newsletter for curated tips & tricks, product updates, industry insights and more.