React Delete Button Onclick Functional Component | React Js Onclick | Functional Component

src/index.js

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";

const userData = [
{
id: "100",
name: "test 1"
},
{
id: "101",
name: "test 2"
},
{
id: "103",
name: "test 3"
},
{
id: "104",
name: "test 4"
},
{
id: "105",
name: "test 5"
}
];
export default class ListComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
users: userData
};
}

onDeleteByIndex(index) {
this.setState({
users: this.state.users.filter((item, i) => i !== index)
});
}

render() {
return (
<div>
<h2>
Delete an item from state array
<hr />
</h2>
<ul>
{this.state.users.map((item, index) => (
<li key={item.id}>
<input
type="button"
value="Delete"
onClick={() => this.onDeleteByIndex(index)}
/>
&nbsp; <span>{item.name}</span>
</li>
))}
</ul>
</div>
);
}
}

ReactDOM.render(<ListComponent />, document.getElementById("root"));


src/styles.css

.App {
font-family: sans-serif;
text-align: center;
}

li {
margin: 2px;
}

li:nth-child(2n + 1) {
background-color: #f1f1f1;
}


package.json
{
"name": "react-delete-an-item",
"version": "1.0.0",
"description": "Delete an item from state array",
"keywords": [],
"main": "src/index.js",
"dependencies": {
"react": "17.0.2",
"react-dom": "17.0.2",
"react-scripts": "4.0.0"
},
"devDependencies": {
"@babel/runtime": "7.13.8",
"typescript": "4.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}


React Delete Button Onclick Functional Component

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.