공통 컴포넌트 구현하기
- 모든 컴포넌트에 공통적으로 사용되는 Button 컴포넌트부터 구현해보자.
Button.jsx
import "./Button.css";
const Button = ({ text, type, onClick }) => {
return (
<button onClick={onClick} className={`Button Button_${type}`}>
{text}
</button>
);
};
export default Button;
Button.css
.Button {
background-color: rgb(236, 236, 236);
cursor: pointer;
border: none;
border-radius: 5px;
padding: 10px 20px;
font-size: 18px;
white-space: noWrap;
}
.Button_POSITIVE {
background-color: rgb(100, 201, 100);
color: white;
}
.Button_NEGATIVE {
background-color: rgb(253, 86, 95);
color: white;
}
App.jsx
import "./App.css";
import { Routes, Route, Link, useNavigate } from "react-router-dom";
import Home from "./pages/Home";
import Diary from "./pages/Diary";
import New from "./pages/New";
import Notfound from "./pages/Notfound";
import Button from "./components/Button";
function App() {
const nav = useNavigate();
const onClickButton = () => {
nav("/new");
};
return (
<>
<Button
text={"수정하기"}
onClick={() => {
console.log("버튼 클릭!-DEFAULT");
}}
/>
<Button
text={"새 글 쓰기"}
type={"POSITIVE"}
onClick={() => {
console.log("버튼 클릭!-POSITIVE");
}}
/>
<Button
text={"삭제하기"}
type={"NEGATIVE"}
onClick={() => {
console.log("버튼 클릭!-NEGATIVE");
}}
/>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/new" element={<New />} />
<Route path="/diary/:id" element={<Diary />} />
<Route path="*" element={<Notfound />} />
</Routes>
</>
);
}
export default App;
- 어떤 버튼인지에 따라서 다른 css를 주기 위해 type props를 이용해 설정해준다.
- 완성
- 모든 컴포넌트에 공통적으로 사용되는 Header 컴포넌트도 구현해보자.
Header.jsx
import "./Header.css";
const Header = ({ title, leftChild, rightChild }) => {
return (
<header className="Header">
<div className="header_left">{leftChild}</div>
<div className="header_center">{title}</div>
<div className="header_right">{rightChild}</div>
</header>
);
};
export default Header;
Header.css
.Header {
display: flex;
align-items: center;
padding: 20px 0px;
border-bottom: 1px solid rgb(226, 226, 226);
}
.Header > div {
display: flex;
}
.Header .header_center {
width: 50%;
font-size: 25px;
justify-content: center;
}
.Header .header_left {
width: 25%;
justify-content: flex-start;
}
.Header .header_right {
width: 25%;
justify-content: flex-end;
}
App.jsx
import "./App.css";
...생략
function App() {
...생략
return (
<>
<Header
title={"Header"}
leftChild={<Button text={"Left"} />}
rightChild={<Button text={"Right"} />}
/>
...생략
</>
);
}
export default App;
- 완성
출처 : 한입 크기로 잘라먹는 리액트
'Language > React.js' 카테고리의 다른 글
[React] 감정일기장 프로젝트 : HomePage 구현하기 (0) | 2024.10.23 |
---|---|
[React] 감정일기장 프로젝트 : 일기 관리 기능 구현하기 (0) | 2024.10.23 |
[React] 감정일기장 프로젝트 : 폰트, 이미지, 레이아웃 설정 (0) | 2024.10.22 |
[React] 감정일기장 프로젝트 : 페이지 라우팅 (0) | 2024.10.22 |
[React] TodoList 프로젝트 : React Context (0) | 2024.10.21 |