Home > other >  Component doesn't Update on Props Change
Component doesn't Update on Props Change

Time:10-10

This component doesn't update even tho props change. prop row is an object. console.log("row", row") does work. and get correct data also console.log("Data", data)

import React, {useState, useEffect} from "react";

const Form = ({row}) => {
  const [data, setData] = useState(row);

  console.log("row", row); //consoleLog1

  useEffect(() => {
    setData(row);
  }, [row]);

  return (
    <>
      {Object.getOwnPropertyNames(data).map((head) => {
        console.log("Data", data);//consoleLog2
        return <input type="text" name={head} defaultValue={data[head] == null ? "" : data[head]} />;
      })}
    </>
  );
};

export default Form;

Update

changing return to <input value={data["ID"}> . and it does update . is there any way to create a form using looping object's properties?

CodePudding user response:

The defaultValue prop is used for uncontrolled components. It sets the starting value, and then it's out of your hands. All changes will be handled internally by input. So when you rerender and pass in a new defaultValue, that value is ignored.

If you need to change the value externally, then you either need to unmount and remount the components, which can be done by giving them a key which changes:

<input key={data[head].someUniqueIdThatChanged} 

Or you need to use the input in a controlled manner, which means using the value prop instead.

value={data[head] == null ? "" : data[head]}

For more information on controlled vs uncontrolled components in react, see these pages:

https://reactjs.org/docs/forms.html#controlled-components
https://reactjs.org/docs/uncontrolled-components.html


P.S, copying props into state is almost always a bad idea. Just use the prop directly:

const Form = ({row}) => {
  return (
    <>
      {Object.getOwnPropertyNames(row).map((head) => {
        return <input type="text" name={head} defaultValue={row[head] == null ? "" : row[head]} />;
      })}
    </>
  );
}
  • Related