Home > Net >  How to change a "sub value" from an initial value?
How to change a "sub value" from an initial value?

Time:07-01

I'm using Next.js with typescript.

I have a form with multiple inputs. I didn't want to make a useState for each input for obvious reasons and I didn't want to use a form-ready library either. I just wanted to find the solution to this.

How can I get the handleInputChange function to change the value of the director's name, for example, in the "initial state"?

const formInitialValues = {
  teamName: "",
  bornAt: "",
  logo: "",
  director: {
    name: "",
    email: "",
    phone: "",
  },
};

const [formData, setFormData] = useState(formInitialValues);

const handleInputChange = (e) => {
  const { name, value } = e.target;

  setFormData({
    ...formData,
    [name]: value,
  });
};

...
<input
  type="text"
  placeholder="Director name"
  name="directorName"
  id="directorName"
  required
  value={formData.director.name}
  onChange={handleInputChange}
/>
...

CodePudding user response:

Maybe you need to use useReducer.

CodePudding user response:

You can do it like below:

const handleInputChange = (e) => {
  const { name, value } = e.target;

  setFormData(() => {
    ...formData,
    director: {
       ...formData.director,
       [name]: value  
    }
  });
};

or using callback of setter method:

setFormData((prevFormData) => ({
  ...prevFormData,
  director: {
    ...prevFormData.director,
    [name]: value
  }
}));
  • Related