Solution
To add multiple values in array in react js, use the push()
method with multiple param, it will add new elements at the end of array. You have to just pass your value 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 multiple items into an array using push()
method.
const arr = [];
arr.push("SortoutCode","ReactJsSnippet");
console.log(arr); // (2) ['SortoutCode', 'ReactJsSnippet']
Example
In this example, we will create an empty array state and add multiple element into array 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("SortoutCode","ReactJsSnippet");
setDomainsList(arr);
}, []);
return (
<div className="App">
<h1>{`Print the Array`}</h1>
<p>{domainsList.toString()}</p>
</div>
);
}
Output