CSS (Cascading Style Sheets)
- 크게 Selector와 Style로 구성되어 있음
h1 { color: green; font-size: 16px; }
- 여기서 h1은 Selector(선택자) 이고, color와 font-size는 속성, green과 16px은 값이다. color: green 과 같이 속성과 값은 하나의 Declaration(선언) 이 된다.
styled-component
css 문법을 사용하면서 결과물을 스타일링된 컴포넌트 형태로 만들어주는 오픈소스 라이브러리
# npm을 사용하는 경우
npm install --save styled-components
# yarn을 사용하는 경우
yarn add styled-components
다음과 같이 터미널에서 설치를 하면 된다.
tagged template literal을 사용하여 css 속성이 적용된 리액트 컴포넌트를 만들어준다.
styled 컴포넌트를 사용하는 기본적인 방법은 다음과 같이 백틱스로 둘러싸인 문자열 부분에
css 속성을 넣고, 태그 함수 위치에는 styled.html태그 형태로 사용한다.
이러면 해당 엘리먼트 태그에 css 속성이 적용된 형태의 리액트 컴포넌트가 만들어진다.
tagged template literal
- literal : 소스코드에 고정된 값
- template literal : 리터럴을 템플릿 형태로 사용하는 자바스크립트 문법, 역따옴표 백틱을 사용
styled-components의 props 사용하기
여기서 props는 해당 컴포넌트에서 사용된 props를 의미한다. props로 dark가 전달되는 여부에 따라 색상을 다르게 할 수 있음
스타일 확장
RoundedButton의 styled 옆 부분을 보면 html 태그가 빠져있고, 대신 Button 컴포넌트가 적혀있다.
이는 Button 컴포넌트의 확장된 컴포넌트라는 뜻이다.
실습 : styled-components를 사용하여 스타일링 해보기
import styled from "styled-components";
const Wrapper = styled.div`
padding: 1rem;
display: flex;
flex-direction: row;
align-items: flex-start;
justify-content: flex-start;
background-color: lightgrey;
`;
const Block = styled.div`
padding: ${(props) => props.padding};
border: 1px solid black;
border-radius: 1rem;
background-color: ${(props) => props.backgroundColor};
color: white;
font-size: 2rem;
font-weight: bold;
text-align: center
`;
const blockItems = [
{
label: "1",
padding: "1rem",
backgroundColor: "red",
},
{
label: "2",
padding: "3rem",
backgroundColor: "green",
},
{
label: "3",
padding: "2rem",
backgroundColor: "blue",
},
];
function Blocks(props) {
return (
<Wrapper>
{blockItems.map((blockItem) => {
return (
<Block
padding={blockItem.padding}
backgroundColor={blockItem.backgroundColor}
>
{blockItem.label}
</Block>
)
})}
</Wrapper>
);
}
export default Blocks;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Blocks from './chapter_15/Blocks';
ReactDOM.render(
<React.StrictMode>
<Blocks />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
다음과 같이 화면에 나타난다. 여기서 개발자 도구에서 스타일 부분을 수정해본다.
align-items를 strect로 변경해보았다. 그러자 다음과 같이 화면에 나타난다.
'React' 카테고리의 다른 글
[React] Appendix A. 리액트 버전18 (3) | 2024.09.02 |
---|---|
[React] react-router-dom v6 (0) | 2024.08.30 |
[React] Context (0) | 2024.08.21 |
[React] Composition 방법과 Inheritance (0) | 2024.08.20 |
[React] 실습 : 섭씨온도, 화씨온도 표시하기 (0) | 2024.08.19 |