Styled-components

Styled-components

·

1 min read

Setting

npm install styled-components

package.json 설치(typescript)

//styled-normalize는 브라우저마다 다르게 보이는 css를 초기화 시키기 위해 다운
npm i --save-dev @types/styled-components

Ex.

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

function Example() {
  const [email, setEmail] = useState("");

  return (
    <ExampleWrap active={email.length}>
      <Button>Hello</Button>
      <NewButton color="blue">Im new Button</NewButton>
    </ExampleWrap>
  );
}

const ExampleWrap = styled.div`
  background: ${({ active }) => {
    if (active) {
      return "white";
    }
    return "#eee";
  }};
  color: black;
`;

const Button = styled.button`
  width: 200px;
  padding: 30px;
`;

// Button 컴포넌트 '상속' : styled.스타일컴포넌트명
const NewButton = styled.Button`
  // NewButton 컴포넌트에 color라는 props가 있으면 그 값 사용, 없으면 'red' 사용
  color: ${props => props.color || "red"};
`;

export default Example;

Props

import React from 'react';
import styled from 'styled-components';

const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: ${props => props.color || 'black'};
  border-radius: 50%;
`;

function App() {
  return <Circle color="blue" />;
}

export default App;

Ex. hover & inner Tag

const StyledListcontainer = styled.div`
  display: flex;
  div {
    margin: 10px 10px 0 0;
    font-size: 12px;
    cursor: pointer;
    &: hover {
      color: gray;
    }
  }
`;

cf. https://kyounghwan01.github.io/blog/React/styled-components/basic/#%E1%84%8B%E1%85%A8%E1%84%89%E1%85%B5