Reputation: 81
I'm trying to rerender the DOM after deleting a item from my webpage. I am new with react and im struggling to get it to work. This is what it looks like:
https://i.sstatic.net/MKnfA.png
What i want it to do is when you click on the pink trash can, the card should get deleted from the DOM without needing to refresh.
This is what the code looks like (i excluded irrelevant code):
const card = (props) => {
function deleteItem() {
fetch('/api/v1/story/'+props.storyID,{
method: 'DELETE',
})
.then(response => response.json())
.then(response => {
if(response['response'] == "success"){
//this is where i would want it to rerender the DOM
}
})
}
return (
<div className="deleteItem" onClick={deleteItem}>
</div>
)
};
export default card;
I hope someone can help me with this. Thanks in advance!
Upvotes: 0
Views: 2579
Reputation: 8947
You should pull this delete function up to the parent component that holds the list of cards. Then pass the function down as props and call it from the child component with the id of the card you want to delete. It's hard to give an exact solution without seeing your code, here is an approximate one.
/* parent */
function deleteItem(id) {
fetch('/api/v1/story/'+id,{
method: 'DELETE',
})
.then(response => response.json())
.then(response => {
if(response['response'] == "success"){
this.setState({ stories: this.state.stories.filter(s => s.storyId !== id) })
}
})
}
return (
<Card onDelete={deleteItem} />
)
const card = (props) => {
const deleteItem = () => props.onDelete(props.storyId)
return (
<div className="deleteItem" onClick={deleteItem}>
</div>
)
}
Upvotes: 3
Reputation: 1074295
With React, you use state to maintain the state of your component (if your component has state, as yours seems to), and you change that state via the built-in setState
(or if you're using hooks, the state function you got from useState
). React will schedule an update of the DOM via your render
method.
This is covered by the React tutorial.
Upvotes: 0