React Styled Components & CSS-in-JS in One Video

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started
Styled Components are CSS-in-JS frameworks for putting your CSS code under your React Components so JS and Styles would live in one place without having the issue of moving back and forth from CSS styles files and your React Components which makes it much easier when it comes to manipulating the styles from one single place using Props.

Styled Components help keep the concerns of styling and element architecture separated and make components more readable. Furthermore, when you have components that rely on JavaScript for their style, Styled Components gives control of those states back to CSS instead of using a multitude of conditional class names.

It is being used by large teams an enormous amount of developers around the globe to bring their React components closer to their styles.

We just need to install it on our React Project (I'm using create-react-app)

npm install styled-components --save 

You don't need more configuration just installing it will make it work on any React project.

Your First Styled Component
Let's try to create a simple button component and define its style using the help of styled-components.

Create a button/ folder under components/ and put index.jsx as the entry point of the component.

import React from "react";
import styled from "styled-components";

//styled will return a React Component with applied style 
const ButtonWrapper = styled.button`
  border: 0;
  background-color: #fff;
  color: #000;
  font-size: 18px;
  border-radius: 4px;
  box-shadow: 0px 0px 8px 2px rgba(15, 15, 15, 0.2);

  &:hover {
    color: rgba(50, 25, 150);
  }
`;

export default function Button(props) {
  return <ButtonWrapper {...props}>{props.children}</ButtonWrapper>;
}

We import styled from styled-components which exports all HTML Standard elements that you can use as a base component then add your custom CSS style to it.

everyone is a function that takes a tagged string literal and parses to apply the CSS you don't have to put braces since ES6 and beyond does recognize string literals that comes after a function name and has to be in (back-tick ``) instead of regular single or double quotes.

You can put regular CSS between the start and close back-tick, also, styled-components uses Stylus CSS Pre-Processor which is familiar to SASS or LESS which can easily allow you to use predefined functions, mixins or have nested children with other many different things you usually do in regular style files.

The styled function will transpile and apply the CSS code to the base component which then returns a new React Component that has the specified style applied so then you can use the new returned component to render the button with custom styles you defined.

You can render the Button Component in your App component and it would get the specified style applied.

If you would like to get CSS Intellisense and code colors for your styled components, make sure to install VSCode Style-Components.

Styled Components with Props

If you have ever been in a situation where you need to apply a custom style to a specific element on a particular event happens like a click or mouse enter or any other DOM event you would have noticed how much hard it is to manipulate an element's style which makes your code looks ugly, less maintainable and harder to manipulate.

With styled-components, you can pass in props like any other React Component where you can toggle between styles or use custom props values to set the style. This way it makes your components much more readable and easier to work with across your project.

Let's add a custom style to the button where we can control from the props.

//We can easily use expressions inside tagged string literals
const ButtonWrapper = styled.button`
  border: 0;
  background-color: #fff;
  color: ${props => (props.clicked ? "blue" : "#000")};
  font-size: ${props => (props.fontSize ? props.fontSize : "18px")};
  border-radius: 4px;
  box-shadow: 0px 0px 8px 2px rgba(15, 15, 15, 0.2);

  &:hover {
    color: rgba(50, 25, 150);
  }
`;

If clicked will be true which means the user has already clicked the button then we can change the color to blue otherwise, we put black text color by default.

Tagged String Literals allows you to put expression inside the string which evaluates javascript code, in this case, styled-components allows us to pass a callback(function) that takes the passed props as argument and returns a string with the applied style value, this way you can manipulate the styles however you want you can even run som pre-calculations on the position.

Also, you have used the & selector to reference the current element and specify a hover style, since styled-components uses Stylus CSS Pre-Processor.

Styling Existing Components

In some cases, you need to apply your own custom styles to a third-party component or an already existing component of yours.

Styled Components accept all kinds of React Components You simply just pass the component refers to the styled function and you define a custom style that gets applied to a new wrapper element that you get to render for the custom style.

One thing you need to make sure you do is passing a classname prop to the existing element on the main container (Wrapper), since styled-components engine uses classnames generations to apply CSS styles.

In this case, I have a simple Link component that renders a hyperlink with (to) prop to link to an external resource.

import React from "react";

export default function Link(props) {
  return (
    <a className={props.className} href={props.to}>
      {props.children}
    </a>
  );
}

Make sure to pass props.classname to an element's classname props otherwise, Styled won't be able to apply your custom defined styles.

Now let's import this component in App.jsx and apply a custom style to it.

import Link from "./components/link";
import styled from "styled-components";
//Pass component reference to styled function 
const CustomLink = styled(Link)`
  transition: color 250ms ease-in-out;
  &:hover {
    color: rgba(50, 25, 150);
  }
  cursor: pointer;
`;

Then you simply could use the CustomLink to render Link with your custom applied styles.

Global CSS Styles

Sometimes you need to apply global styles to all components and just apply regular CSS styles to the DOM.

Fortunately, styles allow us to do that with a very simple and minimal API through the createGlobalStyle function.

Create a global-styles.jsx file under src/ so it holds your global app styles.

/* global-styles.jsx */
import { createGlobalStyle } from "styled-components";

//Make sure to export the returned component from createGlobalStyle function 
export default createGlobalStyle`

  html, body {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    background-color: magenta;
  }
`;

Then you simply render the returned component from createGlobalStyle function in the main entry point of your components hierarchy to make sure it gets applied globally.

/* App.js */
function App() {
  return (
    <div className="App">
      <h3>Hello World</h3>
      <Button clicked={true} fontSize={13}>
        Press Me!
      </Button>
      <Link>Normal Link</Link>
      <CustomLink>Link</CustomLink>
      <GlobalStyles />
    </div>
  );
}

 

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games