Home > database >  Can anyone explain this custom react hook function to me?
Can anyone explain this custom react hook function to me?

Time:10-30

I saw this react form custom hook in a Youtube video and the return statement confuses me. I see that we are returning an array, and I understand using the spread operator but I don't understand why we are doing [e.target.name]:e.target.value especially using square brackets on e.target.name. Can anyone explain? What is this called in Javascript?

import { useState } from 'react';

export const useForm = (initalValues) => {
    const [values, setValues] = useState(initalValues);

    return [
        values,
        (e) => {
            setValues({
                ...values,
                [e.target.name]: e.target.value,
            });
        },
    ];
};

CodePudding user response:

It's used when the property name is computed at runtime. Since you don't know the name of the key in advance, you use this. When this code runs, [e.target.value] will be the name of the input field.

CodePudding user response:

The purpose of that custom hook is to wrap the state dispatch (setValues) around a function to handle an event, most likely front an input field. So I imagine the end result would look something like this:

import useForm from "./useForm"

const FunctionalComponent = () => {
  const [value, handleEvent] = useForm({
    name1: "",
    name2: "" 
  });

  return (
    <input name="name1" value={value} onChange={handleEvent} />
    <input name="name2" value={value} onChange={handleEvent} />
  );
}

The way the hook is using those square brackets helps it select the name property inside the event object.

  • Related