Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- revalidatepath
- 코어자바스크립트
- Form
- React
- 리액트 라우터 돔
- 토이 프로젝트
- 코테
- tanstack query
- 리덕스
- tailwind
- Supabase
- 토이프로젝트
- 그리디
- 타입스크립트
- 프론트엔드
- 동적계획법
- React Query
- 프로그래머스
- styled component
- 코딩테스트
- reduxtoolkit
- JavaScript
- 스택
- react router dom
- TypeScript
- 리액트 패턴
- Next.js
- 리액트
- react pattern
- 자바스크립트
Archives
- Today
- Total
느려도 한걸음씩
children props로 재사용 가능한 컴포넌트 만들기 본문
function App() {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<button
style={{
color: "red",
background: "blue",
width: "100px",
height: "60px",
}}
>
Next
</button>
<button
style={{
color: "red",
background: "blue",
width: "100px",
height: "60px",
}}
>
Previous
</button>
<button
style={{
color: "red",
background: "blue",
width: "100px",
height: "60px",
}}
>
Reset
</button>
</div>
);
}
export default App;
UI 컴포넌트를 제작할때 재사용성을 높일수 있는 children props에 대해 알아보자
위의 코드는 3개의 버튼이 반복되어 사용되고 있고 그 안의 text만 다르게 표시되고 있다 이런 상황에서 children props를 유용하게 사용할수 있다
우선 Button 컴포넌트를 제작한다
function Button() {
return (
<button
style={{
color: "red",
background: "blue",
width: "100px",
height: "60px",
}}
>
</button>
);
}
export default Button;
위의 코드를 참고해 Button 컴포넌트를 만들면 이런 모습일것이다 여기서 컴포넌트에 props를 넘겨주는데 children props를 넘겨준다
function Button({ children }) {
return (
<button
style={{
color: "red",
background: "blue",
width: "100px",
height: "60px",
}}
>
{children}
</button>
);
}
export default Button;
괄호를 이용해 children이 표시될 위치를 지정해준다 쉽게 표현하자면 컴포넌트에 구멍을 뚫어주는것과 같다 사용방법은 다음과 같다
import Button from "./Button";
function App() {
return (
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<Button>Next</Button>
<Button>Previous</Button>
<Button>Reset</Button>
</div>
);
}
export default App;
Button 컴포넌트를 가져와 children의 내용을 태그 사이에 넣어주면된다 위의 예와 같이 단순 텍스트 뿐만 아니라 children으로 컴포넌트 자체를 넘겨주는것도 가능하다
'FE develop > React' 카테고리의 다른 글
React로 HTTP 요청 보내기 - (2) (0) | 2025.03.12 |
---|---|
React로 HTTP 요청 보내기 - (1) (0) | 2025.03.12 |
조건부 렌더링(Conditional Rendering) (1) | 2024.12.03 |
React 컴포넌트에서 DOM으로 변환되는 과정 (1) | 2024.11.15 |
React - 컴포넌트의 세가지 카테고리 (0) | 2024.11.14 |