Home > Software design >  (ReacJS) "Warning: A component is changing an uncontrolled input to be controlled. This is like
(ReacJS) "Warning: A component is changing an uncontrolled input to be controlled. This is like

Time:10-24

The UserForm which is controlled by another controller complains on console as "Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components input span li ul..." Here is the component code :

export default({user}) => {
  if(!user) {
    return <div></div>
  } else {
    const [name,setName] = useState(user.name|| "")
    useEffect(() => {
      setName(user.name);
    }, [user])
              
    return <form>
             <fieldset> 
               <legend> Edit  {user.name }</legend>
               <p> 
                 <label htmlFor={"name"}> Name  </label>
                 <input  id="name" value={name || ""} onChange={e => setName(e.target.value)} />
               </p> 
             </fieldset>
           </form>
  }
}

I tried all fixes suggested on other stackoverflow answers but still gives warning. Is there something I migth missing? Happy Coding...

CodePudding user response:

I've updated your component with this working example.

const { useEffect, useState } = React;

function Example({ user }) {

  const [name, setName] = useState(user.name);

  function handleChange(e) {
    setName(e.target.value);
  }

  useEffect(() => console.log(name), [name]);

  if(!user) return <div></div>;

  return (
    <form>
      <fieldset> 
        <legend>Edit name</legend>
        <input
          id="name"
          value={name}
          onChange={handleChange}
        />
      </fieldset>
    </form>
  )
};

const user = { name: 'Bob' };

ReactDOM.render(
  <Example user={user} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related