I’m working on a project where I need to build a 5*5 grid that is populated by random alphabetic characters(there can be more of the same letter). I’ve built this function, but the problem is that it’s always the same letter showing when rendering and in the log the letter is never repeated.
function Board() { const alphabet = "abcdefghijklmnopqrstuvwxyz"; const [letter, setLetter] = useState(); useEffect(() => { setLetter(alphabet[Math.floor(Math.random() * alphabet.length)]); console.log(letter); }, []); return ( <div className="board"> <p>{letter}</p> <p>{letter}</p> <p>{letter}</p> <p>{letter}</p> </div> ); }
Advertisement
Answer
Represent the whole 2D array in a state and generate the letters for it like below:
const alphabet = "abcdefghijklmnopqrstuvwxyz"; const getRandomLetterRow = (size) => Array.from({ length: size }, () => { return alphabet[Math.floor(Math.random() * alphabet.length)]; }); const generateFrid = (size = 5) => Array.from({ length: size }, () => { return getRandomLetterRow(size); }); function Board() { const [grid, setGrid] = React.useState(generateFrid); return ( <div className="board"> {grid.map((row, rowIndex) => ( <div style={{ display: "flex", flexDirection: "row" }} key={rowIndex}> {row.map((col, colIndex) => ( <div style={{ padding: "5px" }} key={colIndex}> {col} </div> ))} </div> ))} </div> ); } ReactDOM.render(<Board />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>