Frontend Development: Getting Started with Styled Components in React

Peter Jeon·2023년 7월 19일
0

Frontend Development

목록 보기
62/80
post-custom-banner

One of the most popular ways of handling styles in modern React applications is through a library called Styled Components. It utilizes tagged template literals to style your components and removes the mapping between components and styles.

What are Styled Components?

Styled Components allow you to write actual CSS in your JavaScript, meaning your component and its styles are tied together. This provides a more integrated developer experience and eliminates the need to switch between multiple files.

Installing Styled Components

First, we need to install the library. You can do this by running:

npm install --save styled-components

Creating a Styled Component

Here's a basic example of a styled button component:

import styled from 'styled-components';

const Button = styled.button`
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
  padding: 0.5em 1em;
`;

// You can render it like any other React component:
<Button>Click me!</Button>

The Button component now has the styling we defined. Whenever we want a button with this style, we can simply use the Button component.

Props and Styled Components

One of the powerful features of Styled Components is the ability to pass props and alter the styles based on these props:

const Button = styled.button`
  background: ${props => props.primary ? 'palevioletred' : 'white'};
  color: ${props => props.primary ? 'white' : 'palevioletred'};
`;

<Button primary>Primary Button</Button>
<Button>Default Button</Button>

In this example, a primary prop is used to switch between different color schemes.

Conclusion

Styled Components offer a powerful way to handle styles in React. They allow you to directly connect styles to your components, offering a more streamlined developer experience. Furthermore, the ability to use props to control styles adds a layer of dynamism to your styles. This makes it a valuable tool in a modern React developer's arsenal.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

1개의 댓글

comment-user-thumbnail
2023년 7월 19일

좋은 글 잘 읽었습니다, 감사합니다.

답글 달기