단순 코드 기록/RE: React

Styled Components 기초

일일일코_장민기 2024. 5. 22. 04:54
728x90

 

전체코드

더보기
import React from "react";
import "./style.css";
import styled from 'styled-components';

const SimpleButton = styled.button`
    color: white;
    background-color: green;
`;

const LargeButton = styled(SimpleButton)`
    font-size: 50px;
`;

const ReactButton = (props) => {
    console.log("props: ", props)
    return <button className={props.className}>{props.children}</button>
};

const ReactLargeButton = styled(ReactButton)`
    font-size: 50px;
`;

const PrimaryButton = styled.button`
    color: ${function(props){
        console.log('props: ', props)
        if(props.primary){
            return 'white'
        }
        return 'blue';
    }};
    background-color: ${(props) => props.primary ? 'blue' : 'gray'}
`;

export default function App(){
    return(
        <div>
            <SimpleButton>Simple</SimpleButton>
            <LargeButton>Large</LargeButton>
            <ReactButton>React</ReactButton>
            <ReactLargeButton>ReactLarge</ReactLargeButton>
            <PrimaryButton>Normal</PrimaryButton>
            <PrimaryButton primary>PrimaryButton</PrimaryButton>
        </div>
    )
}

 

 

1. Styled Component
- css 코드를 그대로 작성할 수 있는 컴포넌트를 만드는 기술
- 기존에는 style 속성에 {style} 객체를 주입함
--> css를 자바스크립트화 해서 사용하다 보니 기존의 css와 다르게 사용해야 한다는 불편함이 발생
--> stytled.태그명``을 사용하여 ``안에 css 코드를 그대로 사용하면서 객체화한 css를 주입하는 것과 같은 효과를 냄

================================================================

2. Styled Components 설치
npm install styled-components
import styled from 'styled-components';

================================================================

3. Styled Components 사용
3.1 기본적인 사용
const SimpleButton = styled.button`
    color: white;
    background-color: green;
`;
<SimpleButton>Simple</SimpleButton>
- 녹색 배경의 흰 글씨를 가진 버튼 생성

================================================================

3.2 Styled Components 중첩 사용
const LargeButton = styled(SimpleButton)`
    font-size: 50px;
`;
<LargeButton>Large</LargeButton>
- <SimpleButton>에 추가로 폰트 사이즈 50px

================================================================

3.3 기존 컴포넌트에 Styled Components 추가
const ReactButton = (props) => {
    console.log("props: ", props)
    return <button className={props.className}>{props.children}</button>
};
const ReactLargeButton = styled(ReactButton)`
    font-size: 50px;
`;
<ReactButton>React</ReactButton>
<ReactLargeButton>ReactLarge</ReactLargeButton>
- className={props.className}를 부여하여, className이 있으면 적용되도록 함
- Styled Components를 사용하면 임의의 클래스가 부여됨
--> 그냥 컴포넌트인 <ReactButton>에는 css가 적용되지 않음
--> Styled Components가 추가로 부여된 <ReactLargeButton>에는 css가 적용됨

================================================================

3.4 props에 따른 Styled Components 별개 적용
const PrimaryButton = styled.button`
    color: ${function(props){
        console.log('props: ', props)
        if(props.primary){
            return 'white'
        }
        return 'blue';
    }};
    background-color: ${(props) => props.primary ? 'blue' : 'gray'}
`;
<PrimaryButton>Normal</PrimaryButton>
<PrimaryButton primary>PrimaryButton</PrimaryButton>

- Styled Component인 <PrimaryButton>에 기본적으로 글씨색은 파랑, 배경색은 회색을 부여
- prop으로 primary를 갖고 있을 경우에는 글씨색이 흰색, 배경색은 파랑을 부여

================================================================

+++


👌 index.js, app.js 역할, 분리 이유
index.js와 app.js 분리하는 주 이유는 프로젝트의 구조를 명확하게 하고 코드의 관리를 용이하게 하기 위해서다.

index.js
index.js는 애플리케이션의 진입점 역할을 하며 애플리케이션을 시작하는 곳
--> 애플리케이션의 전체적인 중요한 설정들을 포함하고 있다. 이는 해당 애플리케이션의 로직이 아니라 로직에 필요한 설정들을 담고 있다.

app.js
app.js는 애플리케이션의 주요 로직을 담고 있는 핵심 컴포넌트

--> 애플리케이션의 라우팅, 상태 관리 등의 주요 기능을 구현한다.

분리하는 이유
index.js와 app.js를 분리함으로써, 애플리케이션의 설정과 주요 로직을 명확하게 구분할 수 있다.
만약 app.js에서 주요 설정과 로직을 모두 담당하면 app.js의 역할이 너무 커지면서 유지보수에도 좋지 않다.

이렇게 분리하게 되면 각 파일의 역할이 명확해져 코드를 이해하고 유지보수하는데 효율적이다. 

또한 나중에 app.js의 로직을 다른 프로젝트에서 재사용하거나, 교체하는 작업이 필요할 때 분리된 app.js의 로직을 다른 프로젝트의 index.js 설정에 붙여 넣기만 하면 되기에 매우 편리하다.

 

 

'단순 코드 기록 > RE: React' 카테고리의 다른 글

redux toolkit 기초  (0) 2024.05.23
redux 기초  (0) 2024.05.22
Context Api 기초  (0) 2024.05.22
Router 기초  (0) 2024.05.21
React 기초  (0) 2024.05.20