简体   繁体   中英

How to add an array to an empty array in React using hooks

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.

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

编辑 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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM