I have an array and I would like to display one item from the array at random within my render function. Here's what I have now which shows all items:
render() {
return (
<article className="rand-product-cont">
{this.state.products && this.state.products.map((product, index) => (
<article key={index} className="rand-product">
<h3>"{product.name}"</h3>
</article>
))}
</article>
);
};
How can I modify this to show only one product from the array at random? I tried this based on another question I found but it seems to display the same product every time:
render() {
const product = this.state.products.sort(() => Math.random() - Math.random()).slice(0, 1);
return (
<article className="rand-product-cont">
{product && product.map((product, index) => (
<article key={index} className="rand-product">
<h3>"{product.name}"</h3>
</article>
))}
</article>
);
};