skip to Main Content

I have build a editable grid using data from a JSON Array. While editing a textbox, the focus is lost. I understand that the entire grid is re-rendering and this is expected. I therefore added React.memo to both my Grid and Row components. But the problem still persists. What are the patterns/best practices used in React to handle such scenarois? Thanks!

Vercel Playground Link

2

Answers


  1. You have to use defaultValue instead of value on inputs.

    When using controllable input, and onChange function together. It would be pointless to use value on the input.

    Vercel Playground Link

    Login or Signup to reply.
  2. Here is an updated version from your code its working good for me. if you have any question please ask.

    
    const serverRows = [
      { xid: 0, name: "Test 1", age: 20 },
      { xid: 1, name: "Test 2", age: 30 },
      { xid: 2, name: "Test 3", age: 40 },
    ];
    
    const useTable = () => {
      const [rows, setRows] = useState([]);
    
      return {
        id: 0,
        retrieve: () => setRows(serverRows),
        rows: rows,
        changeName: (i, val) => {
          rows[i].name = val;
          setRows([...rows]);
        },
      };
    };
    
    export function Page() {
      const data = useTable();
    
      useEffect(() => {
        data.retrieve();
      }, []);
    
      return (
        <>
          {data.rows.map(row => (
            <div style={{ display: "grid", gridAutoFlow: "column", gap: "10px" }}>
              <span>{row.xid}</span>
              <span>
                <input
                  type="text"
                  value={row.name}
                  onChange={e => data.changeName(row.xid, e.target.value)}
                />
              </span>
              <span>{row.age}</span>
            </div>
          ))}
        </>
      );
    }
    

    I think the Issue was with the row renders as i told you the input is mounted then un-mounted because you are creating the components inside other components. This is a bad practice.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search