Reputation: 51
I am trying to practice forms in react, I am able to successfully display the result onClick, however I want to store them in array so I can map over them and store them in a list. I have tried doing the spread operator but that only returns 1 value. can anyone help? Here is the code in a sandbox.
https://codesandbox.io/s/hidden-tree-p49rw?file=/src/App.jshttps://codesandbox.io/s/nifty-cdn-je05d
Upvotes: 0
Views: 508
Reputation: 1362
You need to pass to setResults a new array, perform the spread on the "result" parameter and then add the input value after that:
setResult([...result, input]);
So let me go over the code to explain the problem.
export default function App() {
const [input, setInput] = useState("");
const [result, setResult] = useState([]);
const handleSubmit = (e) => {
e.preventDefault();
// Spread operator??
setResult(...input, input);
console.log(input);
};
return (
<div className="App">
<form>
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
<button type="submit" onClick={handleSubmit}>
submit
</button>
</form>
<h2>{result}</h2>
</div>
);
}
From what I understand you were trying to create an input (whose value is stored int he "input" state) that submits the data you type in it into an array (the "result" array).
You defined the behaviour of the input correctly:
<input type="text" onChange={(e) => setInput(e.target.value)}></input>
Whenever the user types something into the input, the value (a string) is stored into the input state via set state, which, as a useState hook, takes 1 argument and updates the state to hold it.
Now note that result is also a useState hook, meaning that setResult behaves exactly the same - it expects 1 argument and stores that value into the state.
Here are the problems in your code:
[..."test"]
will give you ```["t", "e", "s", "t"].As a result, every time you submitted the form, you passed the first letter of your input to setResults, changing it from an array to a string holding the first character of the input:
Upvotes: 1