REACT LIBRARY/Styled-Component

Styled-Components로 버튼 만들기

두비_ 2022. 6. 29. 20:31
반응형

src 폴더에 components 폴더를 생성하고 BUtton.js 파일을 생성합니다

Styled-Components를 불러옵니다

import styled from "styled-components";

버튼 컴포넌트 생성

const StyledButton = styled.button``;

먼저 공통적으로 해야할 사이즈를 조절합니다

const StyledButton = styled.button`
  /* 공통 스타일 */
  display: flex;
  outline: none;
  border: none;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  cursor: pointer;
  padding-left: 1rem;
  padding-right: 1rem;
  justify-content: center;
  align-items: center;

  /* 크기 */
  height: 2.25rem;
  font-size: 1rem;

  /* 색상 */
  background: #228be6;
  &:hover {
    background: #339af0;
  }
  &:active {
    background: #1c7ed6;
  }
  
  /* 기타 */
  & + & { // &와 &가 같이 있을 경우, 오른쪽 클래스에 특정 스타일을 적용한다
    margin-left: 1rem;
  }
`;

 

sass처럼 styled-components도 내부에 값을 넣을 수 있습니다 특정 컴포넌트 안에 있는 어떤 클래스에 스타일을 줄 수 있습니다

todtjdgks 컴포넌트를 넣습니다

function Button() {
  return <StyledButton />;
}

그리고 props 설정으로 childern을 가져오고 나머지 Props를 받아옵니다

function Button({ children, ...rest }) {
  return <StyledButton />;
}

StyledButton에게 넣어줍니다

function Button({ children, ...rest }) {
  return <StyledButton {...rest}>{children}</StyledButton>;
}

App.js로 돌아와서 Circle를 없애줍니다

import React from "react";
import styled, { css } from "styled-components";

function App() {
  return;
}

export default App;

AppBlock 컴포넌트를 생성합니다

const AppBlock = styled.div`
  width: 512px;
  margin: 0 auto;
  margin-top: 4rem;
  border: 1px solid black;
  padding: 1rem;
`;

function App() {
  return(
    <AppBlock>
      <Button>Button</Button>
    </AppBlock>
  )
}