Styled Components
를 사용하여 꾸미기 (CSS in JS)Bootstrap
을 사용하여 효율적으로 꾸미기: style 정의를 CSS 파일이 아닌!! JS로 작성된 컴포넌트에 삽입하는 기법
styled
함수 import 해서 사용
import styled from "styled-components";
import Button from "./Button";
styled.button`
// <button> HTML 엘리먼트에 대한 스타일 정의
`;
styled(Button)`
// <Button> React 컴포넌트에 대한 스타일 정의
`;
고정 스타일링
import React from "react";
import styled from "styled-components";
const StyledButton = styled.button`
padding: 6px 12px;
border-radius: 8px;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: gray;
background: white;
`;
function Button({ children }) {
return <StyledButton>{children}</StyledButton>;
}
: React 컴포넌트에 넘어온 props를 사용하여 가변 스타일링
첫번째 방법
import React from "react";
import styled from "styled-components";
const StyledButton = styled.button`
padding: 6px 12px;
border-radius: 8px;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
color: ${(props) => props.color || "gray"};
background: ${(props) => props.background || "white"};
`;
function Button({ children, color, background }) {
return (
<StyledButton color={color} background={background}>
{children}
</StyledButton>
);
}
||
연산자를 사용
두번째 방법
import React from "react";
import styled, { css } from "styled-components";
const StyledButton = styled.button`
padding: 6px 12px;
border-radius: 8px;
font-size: 1rem;
line-height: 1.5;
border: 1px solid lightgray;
${(props) =>
props.primary &&
css`
color: white;
background: navy;
border-color: navy;
`}
`;
function Button({ children, ...props }) {
return <StyledButton {...props}>{children}</StyledButton>;
}
css
함수를 사용해서 여러 개의 CSS 속성을 묶어서 정의primary
prop이 존재하는 경우에만 css
로 정의된 스타일링 적용