|
| 1 | +import { useEffect, useState } from 'react' |
| 2 | + |
| 3 | +import characters from '@/data/characters.json' |
| 4 | +import styles from '../../tablesdemo/TablesDemo.module.css' |
| 5 | + |
| 6 | +function FullTable () { |
| 7 | + const [data, setData] = useState(characters) |
| 8 | + const [headers, setHeaders] = useState([]) |
| 9 | + |
| 10 | + useEffect(() => { |
| 11 | + if (headers.length === 0) { |
| 12 | + setHeaders(Object.keys(data[0]).map((key, id) => ({ |
| 13 | + id, |
| 14 | + name: key |
| 15 | + }))) |
| 16 | + } |
| 17 | + }, [headers, data]) |
| 18 | + |
| 19 | + const handleCellUpdate = (rowId, field, newValue) => { |
| 20 | + if (data[rowId][field] === parseFloat(newValue)) return |
| 21 | + |
| 22 | + setData(prev => |
| 23 | + prev.map(row => |
| 24 | + row.id === rowId ? { ...row, [field]: parseFloat(newValue) } : row |
| 25 | + ) |
| 26 | + ) |
| 27 | + } |
| 28 | + |
| 29 | + const handleKeyDown = (e, rowIndex, colIndex) => { |
| 30 | + // Move cursor to next row |
| 31 | + const { keyCode } = e |
| 32 | + if (keyCode !== 13) return |
| 33 | + |
| 34 | + const nextIndex = (rowIndex === data.length - 1) |
| 35 | + ? 0 : rowIndex + 1 |
| 36 | + |
| 37 | + const nextId = `cell-${nextIndex}-${colIndex}` |
| 38 | + const next = document.getElementById(nextId) |
| 39 | + next?.focus() |
| 40 | + } |
| 41 | + |
| 42 | + return ( |
| 43 | + <div className={styles.container}> |
| 44 | + <div className={styles.subDescription}> |
| 45 | + <h3>Full Table re-rendering (WARNING!) ❌</h3> |
| 46 | + <ul> |
| 47 | + <li>On edit, this table renders the object array data using map(), rendering the full table.</li> |
| 48 | + </ul> |
| 49 | + </div> |
| 50 | + |
| 51 | + <form autoComplete='off'> |
| 52 | + <table> |
| 53 | + <thead> |
| 54 | + <tr> |
| 55 | + {headers?.map(column => ( |
| 56 | + <th key={column.id}> |
| 57 | + {column.name} |
| 58 | + </th> |
| 59 | + ))} |
| 60 | + </tr> |
| 61 | + </thead> |
| 62 | + <tbody> |
| 63 | + {data.map((player, rowIndex) => ( |
| 64 | + <tr key={player.id}> |
| 65 | + {headers?.map((field, colIndex) => ( |
| 66 | + <td key={field.id}> |
| 67 | + {(['id', 'name'].includes(field)) |
| 68 | + ? player[field] |
| 69 | + : <input |
| 70 | + id={`cell-${rowIndex}-${colIndex}`} |
| 71 | + type="text" |
| 72 | + defaultValue={player[field.name]} |
| 73 | + onFocus={(e) => e.target.select()} |
| 74 | + onBlur={(e) => { |
| 75 | + const { value } = e.target |
| 76 | + handleCellUpdate(rowIndex, field.name, value) |
| 77 | + }} |
| 78 | + onKeyDown={(e) => handleKeyDown(e, rowIndex, colIndex)} |
| 79 | + /> |
| 80 | + } |
| 81 | + </td> |
| 82 | + ))} |
| 83 | + </tr> |
| 84 | + ))} |
| 85 | + </tbody> |
| 86 | + </table> |
| 87 | + </form> |
| 88 | + </div> |
| 89 | + ) |
| 90 | +} |
| 91 | + |
| 92 | +export default FullTable |
0 commit comments