Solution
To add an array to an array in react js, use the push()
method it will add new arrays at the end of array. You have to just pass your array into push method.
push()
Method
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
Snippet
In this snippet, we will see short example to add array into an array using push()
method.
const arr = [];
arr.push(["aGuideHub","Infinitbility"]);
arr.push(["aGuideHub","Infinitbility"]);
console.log(arr); // (2) [Array(2), Array(2)]
Example
In this example, we will create an empty array state and add arrays into array state in useEffect
hook, and show the array value in the UI.
Let’s start coding…
App.js
import React, { useEffect, useState } from "react";
export default function App() {
const [domainsList, setDomainsList] = useState([]);
useEffect(() => {
let arr = [...domainsList];
arr.push(["aGuideHub", "Infinitbility"]);
arr.push(["aGuideHub.com", "Infinitbility.com"]);
setDomainsList(arr);
}, []);
return (
<div className="App">
<h1>{`Print the Array`}</h1>
<p>{JSON.stringify(domainsList)}</p>
</div>
);
}
Output