1

I'm trying to create a random name generator where a user would input a bunch of names in a text box, and then it would output a single name from the array.

So far I have the following:

function App() {
  const [firstNames, setFirstNames] = useState(['']);
  
  const submitResults = (e) => {
   e.preventDefault();
   console.log(firstNames.length);
  };
  
  return (
    <main>
      <form onSubmit={submitResults}>
        <div className="container">
          <NameField
            htmlFor="first-selection"
            id="first-selection"
            title="Selection 1"
            value={firstNames}
            onChange={(e) => setFirstNames(e.target.value)}
          />
        </div>
     </form>
    </main> 
   );
}

But when I console.log the firstNames.length, I'm getting the character number instead. For example, if I submit [hello, there], I'll get 12 as the firstNames.length instead of 2. I tried playing around with the onChange, but I'm still not sure how to update the firstNames state so it adds the array properly.

6
  • Because e.target.value is a string. You have to convert that to a JSON array. Try using JSON.parse(e.target.value) Commented Nov 14, 2020 at 5:21
  • If I add JSON.parse and start typing the letter "h" (for example), I'll get an error that says "Unexpected token h at JSON)..." Commented Nov 14, 2020 at 5:31
  • Try this onChange={(e) => setFirstNames([...firstNames,e.target.value])} . Commented Nov 14, 2020 at 5:33
  • That's close, but if I type it'll continuously add whatever I typed before for example, if I type "hello" the array would be ["h", "he", "hel", "hell", "hello"] Commented Nov 14, 2020 at 5:37
  • Are you saying a user enters a comma separated list? Commented Nov 14, 2020 at 5:40

1 Answer 1

1

You've entered a string of comma separated names, so when you want to process this as an array you need to convert the string into an array of strings.

Use String.prototype.split to split the firstNames state by "," to get an array.

firstNames.split(',').length

Edit how-to-add-an-array-to-an-empty-array-in-react-using-hooks

function App() {
  const [firstNames, setFirstNames] = useState("");

  const submitResults = (e) => {
    e.preventDefault();
    console.log(firstNames.split(",").length);
  };

  return (
    <main>
      <form onSubmit={submitResults}>
        <div className="container">
          <input
            htmlFor="first-selection"
            id="first-selection"
            title="Selection 1"
            value={firstNames}
            onChange={(e) => setFirstNames(e.target.value)}
          />
          <button type="submit">Check Names</button>
        </div>
      </form>
    </main>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

@imnewhere Don't forget to use any array filtering and string trimming functions in case the user enters something like " name one , nameTwo, , , three,, " so you can junk the empty strings. Basically just sanitize the input before you consume it elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.