Convert values from input box from a string into an array using react-hook-form

Viewed 1660

I currently have a react form that was created with the custom hook: react-hook-form - https://react-hook-form.com/. I have an input box that I would like to output an array of comma separated values. i.e. "test1", "test2". The current implementation that I have outputs the data as "test1, test2". Is anyone familiar with a way to get the value back as an array and not a string? Here is what I have..

        <label className="form-label" htmlFor="[tenant_authorized_guid]">Tenant_Authorized_Guid(s): 
        <input
          name="[tenant_authorized_guid]"
          placeholder="guid1, guid2, guid3"
          ref={register({
            required: "Required",
            validate: (value) => value !== "",
          })}
        />

I am aware that in javascript I could do something like value.split(",") but I am not sure how to accomplish this with html or the custom hook at this time.

Any help is appreciated.

2 Answers

May be using a controlled component

ex:

  const [value, setValue] = React.useState('');
  const handleChange = (event) => {
    console.log(event.target.value.split(','));
    setValue(event.target.value);
  };
  return (
    <label className="form-label" htmlFor="[tenant_authorized_guid]">
      Tenant_Authorized_Guid(s):
      <input
        name="[tenant_authorized_guid]"
        placeholder="guid1, guid2, guid3"
        value={value}
        onChange={handleChange}
      />
    </label>
  );
Related