Вычислить случайный индекс Math.floor(Math.random() * data.length)
const data = [
{id: 1, author: 'suzy', quote: 'hello world'},
{id: 4, author: 'bob', quote: 'hello world 2'},
{id: 3, author: 'carrie', quote: 'hello world 3'},
{id: 5, author: 'timmy', quote: 'hello world 4'},
{id: 2, author: 'bob', quote: 'hello world 5'},
];
const randIndex = Math.floor(Math.random() * data.length);
console.log(data[randIndex].quote);
RandomQuote
const getRandIndex = arr => Math.floor(Math.random() * arr.length);
const RandomQuote = ({ data, interval = 2000 }) => {
const [quotes, setQuotes] = useState(data);
const [currentQuote, setCurrentQuote] = useState();
/**
* Select a quote at random and remove from the current list of
* selectable quotes, reducing the array length by 1
*/
const getRandomQuote = useCallback(() => {
const randIndex = getRandIndex(quotes);
setCurrentQuote(quotes[randIndex]);
setQuotes(quotes => quotes.filter((_, i) => i !== randIndex));
}, [quotes]);
// Get initial random quote and setup interval and cleanup function
useEffect(() => {
!currentQuote && getRandomQuote();
const timer = quotes.length && setInterval(getRandomQuote, interval);
return () => clearInterval(timer);
}, [currentQuote, getRandomQuote, interval, quotes]);
return (
<main>
<div className="wrapper">
<div className="feature">
{currentQuote && (
<Fragment>
<div className="quote-wrapper">
<h1 className="quote">"{currentQuote.quote}"</h1>
</div>
<div className="author-wrapper">
<span className="author">- {currentQuote.author}</span>
</div>
</Fragment>
)}
</div>
</div>
</main>
);
};