Frontend/Study

[React] React 완벽 가이드 섹션 5 : 렌더링 리스트 및 조건부 Content

BeNI 2022. 3. 29. 03:01
728x90

【글로벌 Best】 React 완벽 가이드 with Redux, Next.js, TypeScript | Udemy


1. 배열 동적으로 렌더링

- 상위 컴포넌트에서 동적으로 변화하는 배열을 props로 받았을 때, 하위 컴포넌트에서 동적으로 렌더링 할 수 있다.

- map함수를 이용하여, jsx를 리턴하도록 하면 된다.

- key를 지정하지 않으면, 웹페이지에서 경고가 난다. (오류는 안남)

* 경고가 나오는 이유는 새로운 아이템이 추가될 때, 어느 인덱스에 추가가 될지 리액트가 모름

  그래서 리액트가 추가될 배열의 모든 상태를 확인하는 작업이 생겨서 비효율적임

const Expense = (props) => {
    return(
        {props.items.map((expense) => (   //props.items 에는 배열이 저장돼있다
            <ExpenseItem
                title={expense.title}
         		amount={expense.amount}
         		date={expense.date}
         		key={expense.id}
            />
        ))}
    );
}

 

 

2. filter함수를 이용하여 특정 요소만 렌더링

- props에서 받아온 배열을 filter함수를 이용해 return 문이 참인 요소들의 배열을 출력하게 할수 있다. 

* 원래 배열은 건드리지 않음 새로운 배열이 생성되는거임

function Expenses(props){
    ...
    const filteredExpenses = props.data.filter((expense)=>{  //props.data는 배열
        return expense.date.getFullYear().toString() === filteredYear;
    });

   return (
     <div>
         <ExpensesList items={filteredExpenses} />
     </div>
   );
}

 

 

3. 조건부 랜더링

1) 삼항 연산자를 이용한 컴포넌트 출력

const Expense = (props) => {
    return (
        ...
        {조건식 ? 조건식의 결과가 참일 때 : 거짓일 때 }
    );
}

 

2) 이항 연산자로 이용해 출력

const Expense = (props) => {
    return (
        ...
        {조건식1 && 조건식의 결과가 참일 때}
        {조건식1의 반대 && 조건식의 결과가 참일 때}
    );
}

 

3) return문 밖으로 빼기

- return문안에 넣는 jsx코드는 코드가 안이쁨

- 좀더 깔끔하게 작성하기 위해서 return문 밖으로 뺌

const Expenses = props => {
   if (props.items.length === 0) {
     return <h2>Found no expenses</h2>;
   }
   
   //조건문의 결과가 거짓일 때 아래 리턴문이 출력됨
   return <ul className="expenses-list">
     {
       props.items.map((expense) => (
       <ExpenseItem
         title={expense.title}
         amount={expense.amount}
         date={expense.date}
         key={expense.id}
       />))
     }
   </ul>
};

728x90