React, styled-components

2024. 12. 6. 09:24웹 개발

설치

npm install && npm install styled-components

 

Blocks.jsx

import styled from "styled-components";

// tagged template literal
const Wrapper = styled.div`
  padding: 1rem;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
  background-color: ${(props) => props.backgroundColor || 'lightgrey'};
`;

// styled-components의 shouldForwardProp을 사용하여 비표준 props (id, className, style 등이 아닌) 의 DOM 전달 제한
// !부정, padding, dark 가 아닌 props 만 전달하겠다는 의미
const Block = styled.div.withConfig({
    shouldForwardProp: (prop) => !["padding", "dark"].includes(prop)
})`
  padding: ${(props) => props.padding};
  border: 1px solid black;
  border-radius: 0;
  background-color: ${(props) => (props.dark === "true" ? "black" : "white")};
  color: ${(props) => (props.dark === "true" ? "white" : "black")};
  font-size: 2rem;
  font-weight: bold;
  text-align: center;
`;

const RoundedBlock = styled(Block)`
  border-radius: 30px;
`;

const blockItems = [
    {
        id: 0,
        label: "1",
        padding: "30px",
        dark: true,
    },
    {
        id: 1,
        label: "2",
        padding: "40px",
        dark: false,
    },
    {
        id: 2,
        label: "3",
        padding: "20px",
        dark: false,
    },
    {
        id: 3,
        label: "1",
        padding: "50px",
        dark: true,
    },
];

function Blocks() {
    return (
        <Wrapper backgroundColor="gray">
            <div>
                {blockItems.map((item) => (
                    <Block
                        key={item.id}
                        padding={item.padding}
                        dark={item.dark.toString()}
                    >
                        {item.label}
                    </Block>
                ))}
            </div>
            <div>
                {blockItems.map((item) => (
                    <RoundedBlock
                        key={item.id}
                        padding={item.padding}
                        dark={item.dark.toString()}
                    >
                        {item.label}
                    </RoundedBlock>
                ))}
            </div>
        </Wrapper>
    );
}

export default Blocks;

 

index.js

import React from "react";
import ReactDOM from "react-dom/client";
import Blocks from "./chapter_15/Blocks";

import "./index.css";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <React.StrictMode>
        <Blocks />
    </React.StrictMode>
);

// https://github.com/soaple/first-met-react-practice-v18/tree/master/src

 

결과

 

https://stackblitz.com/edit/vitejs-vite-yjc1wu?embed=1&file=src%2FApp.jsx

'웹 개발' 카테고리의 다른 글

React, Use Effect 생명주기  (0) 2024.12.09
React, useState 더 깊이 알기  (0) 2024.12.09
React, useContext  (0) 2024.12.05
React, 섭씨온도와 화씨온도 표시하기, Shared State  (1) 2024.12.04
React, SignUp, 폼 만들기  (0) 2024.12.04