In the arr.js file I have some images. I wrote a function for shuffling the elements in the array. I want react to render the shuffled images when the component is first mounted and also when the images are clicked.
Here is what I tried:
import styled from "styled-components";
import React, {useState, useEffect} from "react";
import Arr from "../utils/arr";
const MainContainer = styled.div`
display: grid;
color: white;
padding: 1rem;
margin: auto;
gap: 1rem;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
`
const Main = () => {
const [arr, setArr] = useState(Arr)
const shuffleArrayOnClick = (Arr) => {
for (let i = Arr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i 1));
var tmp = Arr[i];
Arr[i] = Arr[j];
Arr[j] = tmp;
}
return Arr;
}
useEffect(() => {
const shuffle = shuffleArrayOnClick(Arr);
setArr(shuffle);
})
return (
<MainContainer onClick={shuffleArrayOnClick}>
{arr}
</MainContainer>
)
}
export default Main;
The useEffect runs right after the initial render when no dependency array is set. So I expected the images to be shuffled when the component is first mounted. But the shuffle doesn't work when I reload the page. Instead the images get shuffled and re-rendered when I change my code and save it. Also how should I set the onclick function on the array elements? Thanks in advance.
CodePudding user response:
NEVER MODIFY REACT STATE DIRECLY
const shuffleArrayOnClick = (arr) => {
const Arr = [...arr]
for (let i = Arr.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i 1));
var tmp = Arr[i];
Arr[i] = Arr[j];
Arr[j] = tmp;
}
return Arr;
}
You probably want to run this useEffect
once, not million times
useEffect(() => {
const shuffle = shuffleArrayOnClick(arr);
setArr(shuffle);
}, [])