Front-End
[React] Props
SI-AH
2023. 8. 16. 13:20
1. Props
props는 데이터를 전달하기 위해 사용한다.
아래의 코드를 보면, {props.title}를 통해 Header 컴포넌트를 사용할 때 title로 주었던 REACT라는 데이터를 전달해주었다.
# Header 컴포넌트
function Header(props) {
return (
<header>
<h1>
<a href="/">{props.title}</a>
</h1>
</header>
);
}
# Header 컴포넌트 사용
function App() {
return (
<div>
<Header title="REACT"></Header>
</div>
);
}
2. Props 활용
topics라는 배열을 만들고, for문을 사용해 배열에 있는 내용들을 리스트로 만들었다.
for문에 있는 t는 props.topics[i]으로 각 배열의 요소들을 나타내고,
t.id와 t.title은 각 요소에 있는 id값과 title값을 받아와서 리스트를 구성하도록 한다.
# Nav 컴포넌트(props로 list 동적으로 만들기)
function Nav(props) {
const lis = [];
for (let i = 0; i < props.topics.length; i++) {
let t = props.topics[i];
lis.push(
<li>
<a href={"/read/" + t.id}>{t.title}</a>
</li>
);
}
return (
<nav>
<ol>{lis}</ol>
</nav>
);
}
# Nav 컴포넌트 사용
function App() {
const topics = [
{ id: 1, title: "html", body: "html is ..." },
{ id: 2, title: "css", body: "css is ..." },
{ id: 3, title: "jabascript", body: "jabascript is ..." },
];
return (
<div>
<Nav topics={topics}></Nav>
</div>
);
}
이렇게만 하면 아래와 같은 오류가 뜨는데, 그 이유는 key prop가 있어야하기 때문이다.
반복문 안에서만 고유하면 되고, id값을 key prop으로 사용하고자 하므로
아래 코드와 같이 <li key={t.id}> 를 써주면 된다.
# Nav 컴포넌트(props로 list 동적으로 만들기)
function Nav(props) {
const lis = [];
for (let i = 0; i < props.topics.length; i++) {
let t = props.topics[i];
lis.push(
<li key={t.id}>
<a href={"/read/" + t.id}>{t.title}</a>
</li>
);
}
return (
<nav>
<ol>{lis}</ol>
</nav>
);
}
# Nav 컴포넌트 사용
function App() {
const topics = [
{ id: 1, title: "html", body: "html is ..." },
{ id: 2, title: "css", body: "css is ..." },
{ id: 3, title: "jabascript", body: "jabascript is ..." },
];
return (
<div>
<Nav topics={topics}></Nav>
</div>
);
}