Next.js Discord

Discord Forum

Each child in a list should have a unique "key" prop

Unanswered
piscopancer posted this in #help-forum
Open in Discord
got this weird behavior with instancing buttons and passing a key prop. Obviously key is unique being index of .map. So, that's new to me 🤔

### Suggestions in use

      <Suggestions
        suggestions={5}
        search={props.search}
        get={(search) => search.startsWith ?? search.wordsWith ?? []}
        display={(search) => search.startsWith ?? search.wordsWith ?? []}
        button={({ isSelected, i, display, ...htmlProps }) => (
          <button {...htmlProps} key={i} className={classes(isSelected && '!bg-zinc-700', 'flex items-center gap-4 rounded-md px-3 py-1 hover:bg-zinc-700/50 w-full')}>
            <output className='text-zinc-500 text-sm'>{i + 1}</output>
            <span className='text-zinc-200 text-nowrap'>{display}</span>
          </button>
        )}
      />


### Suggestions declaration

export default function Suggestions(/** blabla props */) {
  const suggestions: string[] = /** blabla inner logic */

  return (
    <>
      <ul>
        {suggestions.slice(0, props.suggestions).map((suggestion, i) => {
          const isSelected = searchSnap.selectedSuggestion === i
          return props.button({
            i,
            isSelected,
            onMouseDown: () => selectSuggestion(suggestion),
            display: display[i],
          })
        })}
      </ul>
    </>
  )
}

0 Replies