React Styled Components: Beginners Guide

React Styled Components Tutorial for Beginners
React Styled Components: Beginners Guide

Share:

In today’s post, you’ll learn how to use Styled Components in React with best practices. Using normal styling in React is alright, but if you mistakenly use the same Class name for other components, it can cause some bad effects on your design.

Also, when working on huge projects, there’s no way to keep track of Class Names, there’ll be a point where you might use the same Class Names and break your site. To avoid these issues, there are many ways, but React has an amazing library called Styled Components.

What are React Styled Components?

It is a package that helps you build components that have certain styles attached to them, where the styles only affect which component they were attached to and not any other components.

You can visit the Styled Components official website and read their documentation if you want to learn more, though I will explain all you need to know about it step by step.

Getting Started with Styled Components –

To get started with Styled Components, we need to install and import it first obviously, so let’s do it,

npm install --save styled-components

use the above command to install this Library, and below to import it.

import styled from "styled-components";

Now, let’s initialize the Styled Components, for example, let’s say we want to style a button component,

const Button = styled.button``

this syntax seems weird right? chances are that you might not have used this syntax, it’s actually a JavaScript feature called Tagged Template Literal and yes it was launched with ES6.

So, here the button is a method to the styled object, basically styled is an object that we are importing from styled components and there we are accessing the method called button.

Instead of calling the method using the parenthesis, button(), we are using Tagged Template Literal, again which is the default JavaScript feature.

Here is an article by Webos.com on JavaScript Tagged Template Literal, do check out if you are interested.

So, what’s happening here, whatever we pass between these two backticks will end up in that button method and will return a new button Component.

That styled package has methods for all HTML Elements.

So how can we use it?

Also, check out,
How to style React Components for beginners?

How to use Styled Components?

We can provide the CSS Styles between those backticks ` `, just like below.

const Button = styled.button`
    font: inherit;
    padding: 0.5rem 1.5rem;
    border: 1px solid #8b005d;
    color: white;
    background: #8b005d;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
    cursor: pointer;

  &:focus {
    outline: none;
  }

  &:hover,
  &:active {
    background: #ac0e77;
    border-color: #ac0e77;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
  }
`;

Tip: you can install a library called VScode-styled-components which highlights the styled-components syntax.

Here, we have added the styles in our styled component. A thing to notice is that we don’t need Classes here, as there’s no place to attach it & if you are wondering how to use Pseudo-classes we can just use the “&” operator and it will work just fine.

The button which is returned also applies all the props that are passed to the component, and all the events, types, etc. also can be passed as a prop. Just like this,

<Button type="submit">Add Goal</Button>

How do Styled Components work?

If you inspect the element in the browser, you’ll see the button element obviously, but the interesting part is that it will have super unique classes.

React Styled Components Complete Guide

These class names are dynamically generated by the styled-components package, and what it does, in the end, is it gets the styles we passed in those backticks and wraps it inside those two classes.

Styled components add these classes as global CSS classes, and as the class names are unique for all the styled components we set up, they will never affect any other component in the app.

Styled Components with Conditional Styling & Dynamic Props –

Conditional Styling –

We can also use styled-components in the same file and how can we do it? Let’s say we want to create a div, which will have two elements label and input.

<div className={`form-control ${!isValid ? "invalid" : ""}`}>
    <label>Course Goal</label>
    <input type="text" />
</div>

Now, we’ll transform this above code to the styled component, by creating one, let’s create a styled component called FormControl and it will be a div element.

const FormControl = styled.div`
  margin: 0.5rem 0;

  & label {
    font-weight: bold;
    display: block;
    margin-bottom: 0.5rem;
  }

  & input {
    display: block;
    width: 100%;
    border: 1px solid #ccc;
    font: inherit;
    line-height: 1.5rem;
    padding: 0 0.25rem;
  }

  & input:focus {
    outline: none;
    background: #fad0ec;
    border-color: #8b005d;
  }

  &.invalid input {
    border-color: red;
    background-color: #ffd7d7;
  }

  &.invalid label {
    color: red;
  }
`;

To access the Pseudo classes and child elements or child classes we need to use the “&” operator. This is it, now we can use this component instead of plain div,

<FormControl className={!isValid ? "invalid" : ""}>
        <label>Course Goal</label>
        <input type="text" />
</FormControl>

In FormControl component, we are still using the same className , because what styled-components does is, it passes all the props to the underlying components which is a div element.

So, we can use conditional styling even with the styled-components. But, there’s also another way to do it, and it’s provided by the styled-components package.

Dynamic Props –

We can use this feature by passing props to the styled-components and using them inside our styles.

How can we do it?

Well first we’ll remove the class invalid that we applied previously, and then we’ll pass a prop called invalid which will hold a Boolean value,

<FormControl invalid={!isValid}>
  <label>Course Goal</label>
  <input type="text" />
</FormControl>

here, we are passing a use state hook !isValid , which is a Boolean. Now, inside our styled component, we can use conditional styling, just like this,

const FormControl = styled.div`
  margin: 0.5rem 0;

  & label {
    font-weight: bold;
    display: block;
    margin-bottom: 0.5rem;
// --->
    color: ${props => props.invalid ? "red" : "black"};
// <---
  }

  & input {
    display: block;
    width: 100%;
// --->
    border: 1px solid ${props => props.invalid ? "red" : "#ccc"};
    background-color: ${props => props.invalid ? "#ffd7d7" : "transparent"};
// <---
    font: inherit;
    line-height: 1.5rem;
    padding: 0 0.25rem;
  }

  & input:focus {
    outline: none;
    background: #fad0ec;
    border-color: #8b005d;
  }
`;

As you can see, here we have removed the .invalid class and instead, we are conditionally styling the desired style. I have wrapped the style in arrows as you can see in the above snippet.

To use props passed in styled components, we can use a ${} with curly braces and use a call-back function passing the props as an argument.

That prop will hold all of the props we passed in the styled components, in this case, it’s an invalid prop. So here we are checking if props.invalid is true then set color to "red" and if it’s false set it to "transparent".

That’s It,

I know this can be hard at the beginning to get it completely, but that’s fine, you only need to practice it few times and you’ll be able to wrap your head around it comfortably.

I hope this post was helpful, if it was make sure to share it with your friends who are beginning to learn React. Also, make sure to follow us by pressing the bell icon down-left to never miss any interesting posts on web development.