Rendering Lists & Conditional Content

김민경·2023년 1월 29일
0

FE(WEB) - React

목록 보기
5/13

Outputting Dynamic Lists of Content

filter 함수

const filteredExpenses = props.items.filter(expense => {
	return expense.date.getFullYear().toString() === filteredYear
});

map 함수

- key

Without keys, when adding a new item,
React renders the new item as the last item in the list of divs'
and updates all items and replace their content
in a way that matches the order of the items in the array

=> walks through all the item
and updates the content inside of every item

--> in perfermonce perspective it is inefficient
--> if the item is stateful component, there are possibility for bugs(because of overriding)

=> need keys for React to identify the items!

{filteredExpenses.map((expense, index) => (
	<ExpenseItem
    	⭐key = {expense.id}
        // using index is discouraged
        // since it can still run into bugs 
        // because the index for a given item is always the same
        // and not directly attached to the content of the item
    	title= {expense.title}
        amount = {expense.amount}
        date = {expense.date}
    />
))}

(App.js)

const DUMMY_EXPENSES = [{}, {}, ...] // 객체들로 이루어진 배열

const App =() => {
	const [expenses, setExpenses] = useState(DUMMY_EXPENSES)
    
    const addExpenseHandler = (expense) => {
    	// 이전 state 값에 의존하므로...
    	setExpenses((prevExpenses) => {
        	return [expense, ...prevExpenses];
        }));
    };

}

Rendering Content under Certain Conditions

  • 삼항연산자
  • &&
  • 바깥으로 해당 component 빼기
let expenseContent = <p>No expenses found.</p>

if (filteredExpenses.length > 0) {
	expensesContent = filteredExpense.map((expense) => (
    	<ExpenseItem
        	key = {expense.id}
            title = {expense.title}
            amount = {expense.amount}
            date = {expense.date}
        />
    ));
}

...

return ( {expenseContent} )
  • (if what the component returns changes entirely) two return statements
const ExpenseList = (props) => {

	if (props.items.length === 0) {
    	return (...)
    }
    
    return (...)
}
profile
🏛️❄💻😻🏠

0개의 댓글