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.
e.target.valueis a string. You have to convert that to a JSON array. Try usingJSON.parse(e.target.value)onChange={(e) => setFirstNames([...firstNames,e.target.value])}.