'How do i create duplicates (same keys) in React list?
I'm actually need to create duplicates with same keys. Something like this:
const list = [...items, ...items]
and in my render:
{list.map(item => (
<div key={item.id}>
<Image src={item.image} width="200" height="200" />
</div>
))
I need every duplicate to be absolutely identical so they do not load or process images twice. End result will be:
[image 1] [image 2] [image 1] [image 2]
Solution 1:[1]
This is how you can merge two list, I'm still not very clear what are you asking, do write if have any doubt.
function Test() {
const [firstList, setFirstList] = useState([{ a: "2" }, { b: "3" }]);
const [secondList, setSecondList] = useState([{ c: "4" }, { d: "5" }]);
useEffect(() => {
alert(JSON.stringify(firstList));
});
function mergeList() {
secondList.forEach((d) => setFirstList((firstList) => [...firstList, d]));
}
return <button onClick={mergeList}>Click</button>;
}
export default Test;
Or you can change your function to be like this,(never tried myself) --
function mergeList() {
let previous = firstList;
secondList.forEach((d) => previous.push(d));
setFirstList(previous);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ranu Vijay |
