✔︎ 패키지를 설치
yarn add styled-components
import React from "react";
// styled-components에서 styled 라는 키워드를 import 합니다.
import styled from "styled-components";
const StBox = styled.div`
// 그리고 ``(백틱)을 사용하여 이 안에 스타일 코드를 작성합니다.
width: 100px;
height: 100px;
border: 1px solid red;
margin: 20px;
`;
const App = () => {
// 그리고 우리가 만든 styled-components를 JSX에서 html 태그를 사용하듯이 사용합니다.
return <StBox>박스</StBox>;
};
export default App;
✔︎ styled. 뒤에는 html의 태그가 옵니다. 아래 처럼 내가 원하는 html 태그를 사용해서 styled-components를 만들 수 있습니다.
div ➡️
styled.div
span ➡️styled.span
button ➡️styled.button
import React from "react";
import styled from "styled-components";
// 1. styled-components를 만들었습니다.
const StBox = styled.div`
width: 100px;
height: 100px;
border: 1px solid ${(props) => props.borderColor};
// 4.부모 컴포넌트에서 보낸 props를 받아 사용합니다.
자바스크립트 코드를 사용하기 위해 ${ } (템플릿 리터럴) 를 열어줍니다.
이렇게 리턴하면 빨간 박스의 (props)⇒{ return props.borderColor } 의 값이 === 'red' 가 되고 브라우저는 border: 1px solid red 라는 코드로 인식하여 스타일링이 되는 것 입니다.
margin: 20px;
`;
const App = () => {
return (
<div>
{/* 2. 그리고 위에서 만든 styled-components를 사용했습니다.=StBox
{/* 생성한 styled-component를 부모 컴포넌트(App.js)에서 사용합니다.*/}
{/* 3. 그리고 props를 통해 borderColor라는 값을 전달했습니다. */}
{/* borderColor를 props로 자식컴포넌트인 styled-components StBox에 전달합니다. */}
<StBox borderColor="red">빨간 박스</StBox>
<StBox borderColor="green">초록 박스</StBox>
<StBox borderColor="blue">파랑 박스</StBox>
</div>
);
};
export default App;
공통적으로 들어가야 할 스타일을 적용시 지향함
import styled from "styled-components";
function TestPage(props) {
return (
<Wrapper>
<Title>{props.title}</Title>
<Contents>{props.contents}</Contents>
</Wrapper>
);
}
const Title = styled.h1`
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
font-size: 1.5rem;
margin: 0;
margin-bottom: 8px;
`;
const Contents = styled.p`
margin: 0;
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
font-size: 1rem;
`;
const Wrapper = styled.div`
border: 1px solid black;
border-radius: 8px;
padding: 20px;
margin: 16px auto;
max-width: 400px;
`;
export default TestPage;
GlobalStyle.jsx
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
body {
font-family: "Helvetica", "Arial", sans-serif;
line-height: 1.5;
}
`;
export default GlobalStyle;
BlogPost.jsx
function BlogPost({ title, contents }) {
return (
<>
<p>{title}</p>
<p>{contents}</p>
</>
);
}
export default App;
import GlobalStyle from "./GlobalStyle";
import BlogPost from "./BlogPost";
function App() {
const title = '전역 스타일링 제목입니다.';
const contents = '전역 스타일링 내용입니다.';
return (
<>
<GlobalStyle />
<BlogPost title={title} contents={contents} />
</>
);
}
export default App;
import GlobalStyle from "./GlobalStyle";
import BlogPost from "./BlogPost";
→ 만들어놓은 jsx파일 import