styled-component

ohoho·2022년 10월 17일
0

React

목록 보기
3/12
  1. 패키지 설치
npm i styled-components

1-1. 패키지가 설치되었는지 확인하는방법

package.json파일에서 확인
"dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "styled-components": "^5.3.3",
}
  1. 사용할 js 상단에 import 불러오기
import styled from 'styled-components';
  1. 컴포넌트 생성 & 사용
const Wrap = styled.div`
backgeound:#fff;
`;

return(
<Wrap></wrap>
)
  1. 여러개의 클래스명 사용
<button className={`${buttonColor} ${fontColor}`}>버튼</button>

유의사항

  • 컴포넌트 이름은 대문자로 시작
  • styled뒤에 사용해야할 HTML 태그명 입력
  • 백틱으로 감싸서 작성

중복(공통)으로 들어갈 css 코드 작성시 props사용법

const Box = styled.div`
  background-color: ${(props) => props.bgColor};
  /*background: ${props => props.color || 'black'};*/
  /*props있다면 나오고 없으면 black색 노출*/
  width: 100px;
  height: 100px;
`;

const App = () => {
  return (
    <Wrapper>
      <Box bgColor={"#cf6a87"} />
      <Box bgColor={"#574b90"} />
    </Wrapper>
  );
};

중복된 css를 다른데에도 적용할때

  • styled(ComponentName)와 같이 컴포넌트 명을 괄호 안에 넣어주면 된다.
const Circle = styled(Box)`
  border-radius: 50%;
`

const App = () => {
  return (
    <Wrapper>
      <Box bgColor={"#cf6a87"} />
      <Box bgColor={"#574b90"} />
      <Circle bgColor={"black"} />
    </Wrapper>
  );
};

중복된 css 사용시 태그를 변경할때

  • as를 사용하여 태그명 변경
<Box as="button" bgColor={"#574b90"} />

별도의 css 또는 별도의 props를 가질경우

const Circle = styled.div`
  background: ${props => props.color || 'black'};
  ${props =>
    props.huge &&
    css`
      width: 10rem;
      height: 10rem;
    `}
`;
return <Circle color="red" huge />;

속성변경 css

  • 동일한 속성 일괄 변경 가능
const Input = styled.input.attrs({ required:true, maxLength:10 })`
    background-color: orange;
    margin-right: 5px;
`;

가상선택자

const Box = styled.div`
span {
  background-color: black;
  
  &:hover {
    background-color: white;
  }
}
`;

const BoxWrap = styled.section`
    display:flex;
    width:100vw;
    ${Box} {
      background-color:black;
      color: white;
    }
`;
//BoxWrap안에 위치한 Box 컴포넌트에만 적용하는 방법

css module

  • 클래스 네임을 자바스크립트 오브젝트처럼 사용가능
  • 동일한 클래스명 다른 파일에서 중복 사용 가능
import styles from "./App.module.css";

<div className={styles.wrap}>
	test
</div>

0개의 댓글