Skip to content

Developing with React

Jacob Sommer edited this page Jun 1, 2023 · 10 revisions

Keys and Array Rendering

Often, we will render arrays of components such as by taking an array of review data, mapping each review to a component, and rendering that array of components. Whenever we render an array of components, React requires us to define a key property, otherwise it throws an error in the console.

Key

The key is a unique identifier for that component among the array. The key is responsible for matching states to a component. It does not have to be globally unique but it does need to be unique within that array. One might be tempted to use the index of the element as the key, however, this can cause some issues.

Indices are not unique to the component but rather its position. This might be fine if you are literally rendering a bunch of numbers such as search pagination numbers but in a case such as reviews or search results, this is not okay.

If the order of the components were to change such as if you were to sort reviews and display them in a order, their states would be mismatched due to setting the key to the index. The solution is to use a key that uniquely identifies the component. So for a review, you would use the review id.

BAD

{sortedReviews.map((review, index) => <SubReview review={review} key={index} course={props.course} professor={props.professor} colors={getU(review._id) as VoteColor} colorUpdater={updateVoteColors}/>)}

GOOD

{sortedReviews.map(review => <SubReview review={review} key={review._id} course={props.course} professor={props.professor} colors={getU(review._id) as VoteColor} colorUpdater={updateVoteColors}/>)}

Additional information can be found in React's documentation.

Hooks

wip

What is redux?

Redux is a package that basically allows states to be shared across components... wip

Clone this wiki locally