Home > Software engineering >  React.js - Unique "Key" prop when updating
React.js - Unique "Key" prop when updating

Time:03-08

When I load my page, eveything is fine. When a new show is added, the error appears. Every has a key, I searched all the questions and blogs but can't get it right!

ShowsDisplay.js

import styles from "./ShowsDisplay.module.css";

function ShowsDisplay ({shows, deleteShow}) {
    if (shows.length === 0) {
        return (
            <div key={"nenhumshow"}>
                <p>Nenhum show listado</p>
            </div>
        );
    }
    return (
        <div key={"showsencontrados"}>
            {shows.map((show) => {
                return (
                    <div key={show.id} className={styles.showsDisplay}>
                        <p className={styles.showsTitles}> {show.title}</p>
                        <button className={styles.deleteButton} type="button" onClick={ () => deleteShow(show) }>Delete</button>
                    </div>
                );
            })}
        </div>
    );
}


export default ShowsDisplay;

CodePudding user response:

Try making key as much unique for each child element as you can . Key is the property which tells React DOM , which child element is updated/deleted/added .

{shows.map((show,index) => {
                return (
                    <div key={show.id " "  index} className={styles.showsDisplay}>
                        <p className={styles.showsTitles}> {show.title}</p>
                        <button className={styles.deleteButton} type="button" onClick={ () => deleteShow(show) }>Delete</button>
                    </div>
                );
            })}

CodePudding user response:

It must be about the new show, probably the new show's id is undefined so you get that error

if your id is not number in a row try this

{shows.map((show,index) => {
                return (
                    <div key={show.id??index} className={styles.showsDisplay}>
                        <p className={styles.showsTitles}> {show.title}</p>
                        <button className={styles.deleteButton} type="button" onClick={ () => deleteShow(show) }>Delete</button>
                    </div>
                );
            })}

Or just this ''

  • Related