Created
May 9, 2020 14:48
-
-
Save DennisDurairaj/ebdc15bfbf3d4726ec6b77c1fa6ec533 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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