How to update input defaultValue in React child component when props change?

Viewed 16

I can pass props to the child component, but the input value doesn't change, when I update props (e.g. I send down "second" instead of "first", I can console.log "second" but the input value remains "first".) What could be the problem?

Code example:

// in parent component

const ParentComp = () => {
  const [showEdit, setShowEdit] = useState(false);
  const [currentElement, setCurrentElement] = useState('');

  const myList = [{ label: 'first'}, {label: 'second'}]
    
  const editElement = (el) => {
    setShowEdit(true);
    setCurrentElement(el);
  }

  return (
    <div>
      {myList.map((el, i) => (
        <span key={i} onClick={() => editElement(el)}>
          {el.label}
        </span>
      ))}

      {showEdit && (
        <ChildComponent elData={currentElement} />
      )}
    </div>
)}
// in child component

const ChildComponent = ({ elData }) => {
  const [testInput, setTestInput] = useState(elData.label)
  return (
    <input
      onChange={(e) => setTestInput(e.target?.value)}
      defaultValue={elData.label}
    />
  )

}
1 Answers

I found a working solution but I'm not quite sure how it works.

// old code

<input
   onChange={(e) => setTestInput(e.target?.value)}
   defaultValue={elData.label}
/>
// new code
<input
   onChange={(e) => setTestInput(e.target?.value)}
   value={testInput || ''}
/>

Can anyone explain the difference?

Related