Skip to content

Instantly share code, notes, and snippets.

@DennisDurairaj
Created May 9, 2020 14:48
Show Gist options
  • Save DennisDurairaj/ebdc15bfbf3d4726ec6b77c1fa6ec533 to your computer and use it in GitHub Desktop.
Save DennisDurairaj/ebdc15bfbf3d4726ec6b77c1fa6ec533 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import "./App.css";
const ShuffleFocus = () => {
const [items, setItems] = useState([]);
const itemList = [
{ id: 1, value: "London" },
{ id: 2, value: "Paris" },
{ id: 3, value: "Tokyo" },
{ id: 4, value: "Berlin" },
];
const getShuffledArr = (arr) => {
const newArr = arr.slice();
for (let i = newArr.length - 1; i > 0; i--) {
const rand = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[rand]] = [newArr[rand], newArr[i]];
}
return newArr;
};
useEffect(() => {
const randomizeItemsInterval = setInterval(() => {
setItems(getShuffledArr(itemList));
}, 1000);
return () => clearInterval(randomizeItemsInterval);
}, []);
return (
<div className="App">
{" "}
<div>
{" "}
<h1>Without key</h1>{" "}
{items.length > 0 && items.map((item) => <input value={item.value} />)}{" "}
</div>{" "}
<div>
{" "}
<h1>With index as key</h1>{" "}
{items.length > 0 &&
items.map((item, index) => (
<input key={index} value={item.value} />
))}{" "}
</div>{" "}
<div>
{" "}
<h1>With unique key</h1>{" "}
{items.length > 0 &&
items.map((item) => <input key={item.id} value={item.value} />)}{" "}
</div>{" "}
</div>
);
};
export default ShuffleFocus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment