So, I've got this component here, which If I don't give unique keys, React renders it incorrectly. I can't give this: key={ ${name}${index}
} as a key because name for each element can be edited so this will cause remount... So, How I make these keys unique? just giving index doesn't work...
{stringArray.map((name, index) => (
<Component
key={`${index}_${name}}`}
name={name}
index={index}
onChange={onNameChange}
onDelete={onNameDelete}
/>
))}
One thing I would recommend you do would be to install the uuid npm package here
Not sure if you're using commonjs or modules so try both of these at the top of your file after installing the uuid npm package
// modules
import { v4 as uuidv4 } from 'uuid';
// commonjs
const { v4: uuidv4 } = require('uuid');
Then you should be able to do this instead
// Notice key is now the value of uuidv4()
{stringArray.map((name, index) => (
<Component
key={uuidv4()}
name={name}
index={index}
onChange={onNameChange}
onDelete={onNameDelete}
/>
))}
UUID is a universal unique id. Further reading
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.