Skip to content

Instantly share code, notes, and snippets.

@carefree-ladka
Last active February 12, 2025 13:11
Show Gist options
  • Select an option

  • Save carefree-ladka/b034ee3fea39e7e6f8fb8517eafdcb5b to your computer and use it in GitHub Desktop.

Select an option

Save carefree-ladka/b034ee3fea39e7e6f8fb8517eafdcb5b to your computer and use it in GitHub Desktop.
Clear Boxes in React
import * as React from 'react'
export default function App() {
const [grid, setGrid] = React.useState(Array.from({ length: 3 }, () => Array.from({ length: 3 }, () => false
)))
const cellsRef = React.useRef([])
const timerRef = React.useRef([])
const handleCellClick = (i, j, check) => {
if (grid[i][j] && check) return
if (timerRef.current.length > 0 && check) return
setGrid((prev) => {
const list = prev.map(row => [...row])
list[i][j] = check
check && cellsRef.current.push([i, j])
return list
})
}
React.useEffect(() => {
if (cellsRef.current.length === 9) {
cellsRef.current.forEach(([x, y], idx) => {
timerRef.current[idx] = setTimeout(() => {
handleCellClick(x, y, false)
if (idx === timerRef.current.length - 1) {
timerRef.current = []
}
}, 1000 * (idx + 1))
})
cellsRef.current = []
}
}, [grid])
React.useEffect(() => {
return () => timerRef.current.forEach(id => clearTimeout(id))
}, [])
return <div>
<div className='container'>
{grid.map((row, i) => row.map((col, j) => <div className={`cell ${col ? 'active' : 'inactive'}`} onClick={() => handleCellClick(i, j, true)}></div>))}
</div>
</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment