- A brief history
- Introducing Styled Components
- Installation
- Your first styled component
- Using props to customize components
- Extending an existing Styled Component
- It’s Regular CSS
- Using Vendor Prefixes
- Conclusion
A brief history
Once upon a time, the Web was really simple and CSS didn’t even exist. We laid out pages using tables and frames. Good times.
Then CSS came to life, and after some time it became clear that frameworks could greatly help especially in building grids and layouts, Bootstrap and Foundation playing a big part in this.
Preprocessors like SASS and others helped a lot to slow down the adoption of frameworks, and to better organize the code, conventions like BEM and SMACSS grew in use, especially within teams.
Conventions are not a solution to everything, and they are complex to remember, so in the last few years with the increasing adoption of JavaScript and build processes in every frontend project, CSS found its way into JavaScript (CSS-in-JS).
New tools explored new ways of doing CSS-in-JS and a few succeeded with increasing popularity:
- React Style
- jsxstyle
- Radium
and more.
Introducing Styled Components
One of the most popular of these tools is Styled Components.
It is the meant to be a successor to CSS Modules, a way to write CSS that’s scoped to a single component, and not leak to any other element in the page.
(more on CSS modules here and here)
Styled Components allow you to write plain CSS in your components without worrying about class name collisions.
Installation
Install styled-components using npm or yarn:
npm install styled-components
yarn add styled-components
That’s it! Now all you have to do is to add this import:
import styled from 'styled-components'
Your first styled component
With the styled
object imported, you can now start creating Styled Components. Here’s the first one:
const Button = styled.button`
font-size: 1.5em;
background-color: black;
color: white;
`
Button
is now a React Component in all its greatness.
We created it using a function of the styled object, called button
in this case, and passing some CSS properties in a template literal.
Now this component can be rendered in our container using the normal React syntax:
render(<Button />)
Styled Components offer other functions you can use to create other components, not only button
, like section
, h1
, input
and many others.
The syntax used, with the backtick, might be weird at first, but it’s called Tagged Templates, it’s plain JavaScript and it’s a way to pass an argument to the function.
Using props to customize components
When you pass some props to a Styled Component, it will pass them down to the DOM node mounted.
For example here’s how we pass the placeholder
and type
props to an input
component:
const Input = styled.input`
//...
`
render(
<div>
<Input placeholder="..." type="text" />
</div>
)
This will do what you think, inserting those props as HTML attributes.
Props instead of being blindly passed down to the DOM can also be used to customize a component based on the prop value. Here’s an example:
const Button = styled.button`
background: ${props => (props.primary ? 'black' : 'white')};
color: ${props => (props.primary ? 'white' : 'black')};
`
render(
<div>
<Button>A normal button</Button>
<Button>A normal button</Button>
<Button primary>The primary button</Button>
</div>
)
Setting the primary
prop changes the color of the button.
Extending an existing Styled Component
If you have one component and you want to create a similar one, styled slightly differently, you can use extend
:
const Button = styled.button`
color: black;
//...
`
const WhiteButton = Button.extend`
color: white;
`
render(
<div>
<Button>A black button, like all buttons</Button>
<WhiteButton>A white button</WhiteButton>
</div>
)
It’s Regular CSS
In Styled Components, you can use the CSS you already know and love. It’s plain CSS. It is not pseudo CSS nor inline CSS with its limitations.
You can use media queries, nesting and anything else you might need.
Here’s an example of a media query:
const Button = styled.button`
color: green;
@media screen and (max-width: 800px) {
color: black;
}
`
Using Vendor Prefixes
Styled Components automatically add all the vendor prefixes needed, so you don’t need to worry about this problem.
Conclusion
That’s it for this Styled Components introduction! These concepts will help you get an understanding of the concept and help you get up and running with this way of using CSS in JavaScript.
Download my free React Handbook
More react tutorials:
- A React simple app example: fetch GitHub users information via API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to a child component via React Router
- Create an app with Electron and React
- Tutorial: create a Spreadsheet using React
- The roadmap to learn React
- Learn how to use Redux
- Getting started with JSX
- Styled Components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- React Components
- The Virtual DOM
- React Events
- The React State
- React Props
- The React Fragment
- The React Context API
- React PropTypes
- React concepts: declarative
- React: How to show a different component on click
- How to loop inside React JSX
- Props vs State in React
- Should you use jQuery or React?
- How much JavaScript you need to know to use React?
- Introduction to Gatsby
- How to reference a DOM element in React
- Unidirectional Data Flow in React
- React Higher Order Components
- React Lifecycle Events
- React Concept: Immutability
- React Concept: Purity
- Introduction to React Hooks
- Introduction to create-react-app
- React Concept: Composition
- React: Presentational vs Container Components
- Code Splitting in React
- Server Side Rendering with React
- How to install React
- CSS in React
- Using SASS in React
- Handling Forms in React
- React StrictMode
- React Portals
- React Render Props
- Testing React components
- How to pass a parameter to event handlers in React
- How to handle errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- React, how to transfer props to child components
- How to get the value of an input element in React
- How to use the useState React hook
- How to use the useCallback React hook
- How to use the useEffect React hook
- How to use the useMemo React hook
- How to use the useRef React hook
- How to use the useContext React hook
- How to use the useReducer React hook
- How to connect your React app to a backend on the same origin
- The Reach Router Tutorial
- How to use the React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix the `dangerouslySetInnerHTML` did not match error in React
- How I fixed an issue with a React login form state and Browser autofill
- How to configure HTTPS in a React app on localhost
- How to fix the "cannot update a component while rendering a different component" error in React
- Can I use React hooks inside a conditional?
- Using useState with an object: how to update
- How to move around blocks of code with React and Tailwind