Last active
October 26, 2020 01:08
-
-
Save Pavneet-Sing/3259b10769d056e19864099d8a7d45a5 to your computer and use it in GitHub Desktop.
To efficiently implement the array update events in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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