Search code examples
javascriptreactjscontrolled-component

Changing input of controlled component changes property value to undefined


I have an array of default values in a useState. Upon an onChange event via a select, the properties in the array are changed to undefined. I've been reading up on controlled components and I think I've missed something silly.

Here is a codesandbox.

const [config, setConfig] = useState([{
  carType: "Sedan",
  carColor: "Red"
}]);

// onChange
const setCarType = (e) => {
  setConfig({ ...config[0], carType: e.target.value });
};

const { carType, carColor } = config[0];

I thought that I could use the spread operator here in order to copy the two properties of config[0] into two separate constants. I originally had the config in an object but was thrown an error "Objects are not valid as a react child".


Solution

  •   const setCarType = (e) => {
        setConfig([{ ...config[0], carType: e.target.value }]);
      };
    
      const setCarColor = (e) => {
        setConfig([{ ...config[0], carColor: e.target.value }]);
      };
    

    When you were setting config, you were setting a new object as config but it was initialized as an array of objects. So config[0] was undefined cause config was no more an array. Try the above code, it will solve the issue.