Get my new tutorials in your inbox every week
difference between .js and .jsx files

How do I add multiple items to an array with ReactJS?

ReactJS is not a language per se. It’s built on top of JavaScript. So, as such, there is no other way to add items to an array. But its the same as what we do in core JavaScript. Some examples below,

var arr = [1,2,3,4]; //initial array
 
//different ways to add items
arr.push(5,6); //[1,2,3,4,5,6]
arr.unshift(5,6); //[5,6,1,2,3,4]
arr.splice(arr.length, 0, 5,6); //[1,2,3,4,5,6]
arr.concat([5,6]); //returns a new array with [1,2,3,4,5,6]
 
//es6 spread operator
arr = [...arr, 5,6]; //[1,2,3,4,5,6]

Below, I have a simple example of a ReactJS app showing the same…

class MyApp extends React.Component {
	constructor(props) {
		super(props);
		this.arr = [1,2,3,4];
	}	
	componentDidMount() {
		//Add items to the array
		this.arr.push(5,6);
	}
	render() {
		return (
			<div>
				<h3>My App</h3>
				<ul>
				{this.arr.map((item, index) => {
					return (<li key={index}>{item}</li>)
				})}
				</ul>
			</div>
		);
	}
}

Cheers 🙂

Write a Comment

Your email address will not be published. Required fields are marked *