Table of contents
No headings in the article.
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.
Styled-Components
Styled-components is a component-level style library built to use with React and in React frameworks. This library allows you to include JavaScript logic in your CSS style rule, so you can apply CSS-in-JS. Using the styled-components library for your application makes it relatively easy to create dynamic style rules for your React components.
Advantages of Styled-Components
- Easy to learn
- They generate unique class names for styles and help you to avoid class name collisions and bugs in your code
- It’s easier to create dynamic and adaptive styles with styled-components
- Component-level styling makes it easy to debug styling issues
- Styled-components support server-side rendering; this is useful when you’re working with NextJS (a React framework) or when you configure server-side rendering for your React application
- Styled-components provide Sass style support
- Support for custom style themes
- Easy setup for style themes
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, we need to create a React application and install the styled-components library by running one of the commands below:
yarn add styled-components
or
npm install --save styled-components
Once we install the library, we will start styling the application.
Styling a React App with Styled-Components
The styled-components library allows you to create component-level styles for your React application by calling the styled interface. We’ll pass the style rules to the component using tagged template literals:
import styled from "styled-components";
const [Component Name] = styled.[DOM Element]`
[CSS Style Rules]
`;
From the code block above, we have a component name follows the convention for naming components in React. From the styled object, we will access the property representing the DOM element we want to create and style. The style rules are passed inside the template literals.
Using the format above to style a nav for a real-life project, we will have something similar to the code block below:
...
function App(){
return <Nav />
}
const Nav = styled.nav`
background-color: #fff;
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 40px;
border-bottom: 1px solid #878787;
`;
The code block above will create a nav element with specified styles applied. You can also pass in props to styled components or insert JavaScript logic:
const MyComponent = styled.div`
opacity: ${(props)=> props.show ? 1 : 0};
`;
In the code block above, we are conditionally applying a value to the opacity style based on the value of the show props. When we set "show" to true on MyComponents, the div's opacity is set to 1. It’s set to 0 when the value is false. Styled-components also allow you to create global styles with the createGlobalStyle
function; this is a special function that allows you to create a styled component that is not scoped to a specific component.
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
[global style rules]
`;
function App(){
return (
<div classname="app">
<GlobalStyle />
<Nav>
<BrandText>Theme With Styled-Components</BrandText>
</Nav>
...
</div>
);
}
The code block above creates a global styled component that we can use to style components outside its scope.
Theming React
Styled-components also allow you to provide different themes for your React application; we’ll explore how to achieve this in this section and the following one. The theming feature for styled-components is made possible with the ThemeProvider
wrapper component; ThemeProvider
provides the theme to all of the components underneath it using the context API. The component accepts a theme rule object as a value to its theme prop, and we can access the theme rule in all styled-components via prop.theme
.
Following this, we will be setting up a theme object for the project in the theme folder.
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;
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
:
import styled, { ThemeProvider } from "styled-components";
import theme from "./theme";
...
function App() {
const [currentTheme, setCurrentTheme] = useState("light");
...
return (
<ThemeProvider theme={theme[currentTheme]}>
<Nav>
<BrandText>Theme With Styled-Components</BrandText>
<ToggleButton>
currentTheme={currentTheme}
onClick={() => {
if (currentTheme === "light") {
setCurrentTheme("dark");
} else {
setCurrentTheme("light");
}
}}>
<span></span>
</ToggleButton>
</Nav>
...
</ThemeProvider>
);
}
From the code block above, we have the currentTheme
state; this controls the theme rule to pass to the theme providers. The ToggleButton
component allows us to toggle between light and dark themes.
Using Themes in Styled-Components
To use the theme rules in the component styles, we will need to access the theme from the props
object:
...
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};
`;
...
In the code block above, we are destructuring the theme property from the props
object. This will give us access to all the theme rules. Using the code sample above we have:
background-color: ${({ theme }) => theme.color.background};
This will apply the primary color specified in the theme rule based on the current theme selected.
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 by leveraging the styled-components ThemeProvider
component. 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/.