styled-components

samanthaelainef

Samantha Frangi

Posted on July 17, 2022

styled-components

A couple nights ago, I was working on a project that I'm building in React.

Making sure I'm referencing class names correctly and importing CSS files in the right places was something I've done before. This time, none of my styles were applying and I'd done all the troubleshooting I could. So I hit up Google and look up "styling in React". Very broad search terms, I know, but it helped me find styled-components.

What is styled-components?

In short, styled-components allow you to write CSS in JS files.

I'd never used styled-components before, and I only remembered hearing about it very briefly.

First, I had to install the styled-components package. To do so I ran:

npm i styled-components

Then, I got to work on my Footer.js file.

The Footer component came out like this:

import { Link } from 'react-router-dom'
import styled from 'styled-components'

const SiteFooter = styled.footer `
  position: fixed;
  background-color: #8FBB99;
  bottom: 0;
  width: 100%;
`

const linkStyle = {
  margin: "1rem",
  textDecoration: "none",
  color: "white",
}


function Footer() {
  return (
    <SiteFooter>
      <Link to="/contact" style={linkStyle}>
        Contact
      </Link>
    </SiteFooter>
  )
}

export default Footer;
Enter fullscreen mode Exit fullscreen mode

And voila! We have a footer 🎉

Very basic footer

By importing styled from the styled-components package, I am able to create a React component that will render the selected HTML element.

Let's say I wanted to make a div that is a red square. Styled-components allows me to reference the red square as a component that I might name ... RedSquare.

const RedSquare = styled.div`
    width: 100px;
    height: 100px;
    background-color: red;
`
Enter fullscreen mode Exit fullscreen mode

In SiteFooter, you'll notice that the CSS is written inside of back ticks - these are tagged template literals. An easy way to think of tagged template literals is like a function.

Benefits of using styled-components

A footer was a great reason for using styled-components because it requires minimal styling.

Since I've handled all the styling in the component itself, I don't have to search through files for the class-name and make changes. Styling, markup, and logic are all in one file and makes for a smooth developer experience.

This has been quite the unlock in my deep dive into React!

What are your favorite things about React?

💖 💪 🙅 🚩
samanthaelainef
Samantha Frangi

Posted on July 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Meme Generator Sample With React
Mountain! - A Meta Analysis
react Mountain! - A Meta Analysis

September 15, 2022

styled-components
react styled-components

July 17, 2022