How to create React Components using Sty ...

How to create React Components using Styled Components - For beginners

Jul 03, 2022

In this post, I'll explain how to create a React component using Styled Components. I've assumed that you already have created your React project and installed the styled-components in your project (you can run yarn add styled-components or npm install styled-components to install it). With this in mind, hands-on!

1) First, we will need to create a new style.js file importing the styled from 'styled-components' library. After that, we should export a variable assigned to our component creating the desired element through the styled object. In our case, we'll create a container containing a h1 element inside. Example:

import styled from 'styled-components';

export const Container = styled.div`
`

2) Now, it's time to style our component. As it's a container, let to centralize our h1 element in the container. Example:

import styled from 'styled-components';

export const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;
`

3) Now, we'll style our h1 element that is into our container. To do that, we'll need to declare the h1 styling as a cascade using the operator "&". Example:

import styled from 'styled-components';

export const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
width: 100px;
height: 100px;

& h1 {
color: red;
}

`

4) Finally, all we should do is, import our Container from our style.js file inside our application. Example:

import { Container } from './styles.js'

export default function MyApp(){
  <Container>
    <h1>My Title</h1>
  </Container>
}

It was the first step in how to use Styled Component in our projects. I wish it was helpful for someone. If this topic has helped you, consider buying me a coffee.

Enjoy this post?

Buy pablosilvadev a coffee