Skip to content

Instantly share code, notes, and snippets.

@Pavneet-Sing
Last active October 26, 2020 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pavneet-Sing/3259b10769d056e19864099d8a7d45a5 to your computer and use it in GitHub Desktop.
Save Pavneet-Sing/3259b10769d056e19864099d8a7d45a5 to your computer and use it in GitHub Desktop.
To efficiently implement the array update events in React
import React, { Component } from "react";
import "./style.css";
export default class App extends Component {
state = {
cart: ["Corn", "Potato"],
};
addNewItem = () => {
this.setState((prevState) => ({
cart: [...prevState.cart, this.inputElement.value],
}));
};
render() {
return (
<div>
<input type="text" ref={(el) => (this.inputElement = el)} />
<button onClick={this.addNewItem}> Add Item </button>
<ol>
{this.state.cart.map((subItems, sIndex) => {
return <li key={subItems + sIndex}> {subItems}</li>;
})}
</ol>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment