Encountered two children with the same key, .$block-text-2. Keys should be unique so…
- User
Encountered two children with the same key,
.$block-text-2. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.const newId =
block-${id}-${newBlockCount};whats a better way for a unique id
- Assistant
To ensure that IDs are unique in a React application (or any scenario where you need unique identifiers), you should use a combination of a unique source (like a timestamp or a random number) and an incrementing counter or a unique property from the data being rendered. Here are several methods you might consider for generating unique IDs:
- User
const [blockCounter, setBlockCounter] = useState(0);
// Generate a new ID function const generateNewId = () => { const uniqueId =
block-${id}-${blockCounter}; setBlockCounter(prev => prev + 1); return uniqueId; };// Usage const newId = generateNewId();
I like this idea:
how would it work with:
const handleBlockRemove = (id) => { };
and
const handleBlockAdd = (width, height, content, id, type) => { };
- Assistant
- User
i already have:
const [blocks, setBlocks] = useState([]);// Current blocks on the grid const [newBlockCount, setNewBlockCount] = useState(0);// Counter for new blocks added
use these to work with our concept of a generated id
- Assistant
- User
I just checked my code and your code suggestion to fix:
"Encountered two children with the same key,
.$block-text-2. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version."and Im already doing this:
import React, { useState } from 'react';
const BlockManager = () => { const [blocks, setBlocks] = useState([]); // Current blocks on the grid const [newBlockCount, setNewBlockCount] = useState(0); // Counter for new blocks added
code - Assistant
- User
which of the two is faster:
const newId =
block-${id}-${newBlockCount}-${Date.now()}; const newId =block-${id}-${newBlockCount}-${Math.random().toString(36).substr(2, 9)}; - Assistant