DEV Community

Carlos Guzmán
Carlos Guzmán

Posted on

How to use basic styled-components in React

Styled Components, is a library used in react for write CSS into Javascript files, this is good usually when you want to have your CSS code into the component or create a specific component with style and personalized tag.

To install the library, into your react project run:

npm install --save styled-components. 
Enter fullscreen mode Exit fullscreen mode

Styled-components utilize tagged template literals to style your components. It removes the mapping between components and styles. This means that when you are defining your styles, you are actually creating a normal React component, that has your styles attached to it.

After installing the library, you can use these functions in your component.

Remember to import the library into JS File.

import styled from 'styled-components'
Enter fullscreen mode Exit fullscreen mode

Example:

`// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// Use Title and Wrapper like any other React component – except they're styled!
render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);`
Enter fullscreen mode Exit fullscreen mode

If you want more information, you can see styled-components documentation in the next link.

https://styled-components.com/docs/basics#installation

Top comments (0)