delete html react code example
Example 1: react hooks delete item from array
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const App = () => {
const defaultList = [
{ name: "ItemOne" },
{ name: "ItemTwo" },
{ name: "ItemThree" }
];
const [list, updateList] = useState(defaultList);
const handleRemoveItem = (e) => {
const name = e.target.getAttribute("name")
updateList(list.filter(item => item.name !== name));
};
return (
<div>
{list.map(item => {
return (
<>
<span name={item.name} onClick={handleRemoveItem}>
x
</span>
<span>{item.name}</span>
</>
);
})}
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Example 2: how to delete a html tag element in react
const Row = function(props){
const {checked, value, onChange, onChecked} = props;
return (
<div>
<input
type="checkbox"
checked={checked}
onChange={onChecked}
/>
<input type ="text" value={value} onChange={onChange}/>
</div>
);
}
class App extends React.Component {
constructor(props){
super(props);
this.state = {
rows: [
{value: 'row1', checked: false},
{value: 'row2', checked: true},
{value: 'row3', checked: false},
]
};
}
updateValue = (e, idx) => {
const rows = [...this.state.rows];
rows[idx].value = e.target.value;
this.setState({
rows,
});
}
onChecked = (idx) => {
const rows = [...this.state.rows];
rows[idx].checked = !rows[idx].checked;
this.setState({
rows,
});
}
addRow = () => {
const rows = [...this.state.rows,
{value:'', checked: false}
];
this.setState({
rows,
});
}
deleteRows = () => {
this.setState({
rows: this.state.rows.filter(e => !e.checked)
});
}
render(){
return(
<div>
{this.state.rows.map((row, idx) => {
return(
<Row
key={idx}
value={row.value}
checked={row.checked}
onChange={(e) => this.updateValue(e, idx)}
onChecked={() => this.onChecked(idx)}
/>
)
})
}
<button onClick={this.addRow}>
add
</button>
<button onClick={this.deleteRows}>
delete
</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);