Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 17, 2022 07:19 pm GMT

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;

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;`

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?


Original Link: https://dev.to/samanthaelainef/styled-components-3d4g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To