컴포넌트를 리스트로 표시하기
React 컴포넌트를 리스트로 표시하는 방법
섹션 제목: “React 컴포넌트를 리스트로 표시하는 방법” author: Onejay createdAt: 2024-08-29 updatedAt: 2024-08-29List 의 map 함수로 컴포넌트 표시하기
섹션 제목: “List 의 map 함수로 컴포넌트 표시하기”-
최상위 tag 의
key를 중복되지 않는 값으로 설정해주어야 한다.-
return ({list.map((item, index) => {return (<div key={`${index}`}><span>{item}</span></div>);});});
-
-
전체 코드
const prepare = async () => {return new Promise<string[]>((resolve, reject) => {setTimeout(() => {resolve(['Apple', 'MS', 'Google']);}, 300);});};export default function index() {const [result, setResult] = React.useState<string[]>([]);const [loading, setLoading] = React.useState<boolean>(true);const [error, setError] = React.useState<boolean>(false);useEffect(() => {prepare().then(result => {setResult(result);setLoading(false);}).catch(err => {console.error('fail-prepare', err);setError(true);});}, []);return (error? <div><h1>Error!!!</h1></div>:loading? <div><h1>Lodaing...</h1></div>: {result.map((item, index) => {return (<div key={`${index}`}><span>{item}</span></div>);});});}