1 | initial version |
You can use the useState hook to create an empty nested array and then add user input to it using the set method. Here's an example:
import React, { useState } from "react";
function MyComponent() {
const [nestedArray, setNestedArray] = useState([]);
const addInputToNestedArray = (input) => {
setNestedArray((prevNestedArray) => [...prevNestedArray, input]);
};
return (
<div>
<input
type="text"
onChange={(e) => {
addInputToNestedArray(e.target.value);
}}
/>
<button onClick={() => addInputToNestedArray("default value")}>
Add default value
</button>
<pre>{JSON.stringify(nestedArray, null, 2)}</pre>
</div>
);
}
In this example, we create an empty nested array using the useState hook:
const [nestedArray, setNestedArray] = useState([]);
We then define a function called addInputToNestedArray
that takes an input and adds it to the nested array using the set method. We use the spread operator (...
) to create a new array that contains the previous nested array with the new input appended to the end:
const addInputToNestedArray = (input) => {
setNestedArray((prevNestedArray) => [...prevNestedArray, input]);
};
In the render method, we create an input field that calls the addInputToNestedArray
function on change. We also create a button that adds a default value to the nested array. Finally, we display the nested array using JSON.stringify
.