Javascript .map(...) with React Component

Viewed 75

In my React code I have something like

{elements.map((element) => {
   return (
      <div>
           {renderDate(element.date)}
      </div>
   )
}})}

where

const renderDate = (date: string) => {
    return (
        <div>
            <span className="date">
                {date}
            </span>
        </div>
    )
}

When I look at the UI, I see that all the elements on the page have the same date as the last date in the elements array. However I want to maintain each elements date and not have it been overwritten. Can anyone offer suggestion? Should I turn .map(...) into .forEach(...)?

1 Answers

Without further details I can't say for sure, but it might just be syntax. I think you have an extra closing brace (}) on the last line. Try this:

{elements.map((element, i)=> (
  <div key={i} >
    {renderDate(element.date)}
  </div>
))}

As mentioned, you also need to add a key prop. If the elements array is not going to be updated, causing the component to re-render, a simple index key like above will work. Alternatively, if the dates are all unique you could use <div key={element.date}>, or another value which is unique to each item.

Related