I have a component that is reused in other components but there is a problem that the code handle action events (e.g: onDelete) are repeated too many times. I have to handle onDelete in all places where PostCard is used even though the logic code makes no difference except at the Home page. So is there any way I can avoid the repetition of handleDelete? Respect any ideas. I’m new to React.js, hope you guys can help me!
PostCard component:
function PostCard ({ item, onDelete }) => {
return (
<div onClick={() => onDelete(item.id)}>{item.title}</div>
)
}
PostCard using in Home page:
const HomePage = () => {
function handleDelete() {
// only mutate array to re-render list (not redirect)
}
return (
<>
{postList.map(post => (
<PostCard item={post} onDelete={handleDelete} />
))}
</>
)
}
PostCard using in detail page:
const DetailPage = () => {
function handleDelete() {
// redirect to home page after delete
}
return (
<PostCard item={post} onDelete={handleDelete} />
)
}
PostCard using in another page:
const AnotherPage = () => {
function handleDelete() {
// redirect to home page after delete
}
return (
<PostCard item={post} onDelete={handleDelete} />
)
}
>Solution :
you can create a context on a higer level than those components so you can pass the postList state and handleDelete function as context to them for example:
const App = () => {
export const PostContext = createContext();
const [postList, setPostList] = useState([]);
const handleDelete = (postId) => {
// delete logic
};
//...
return (
<PostContext.Provider value={{ postList, handleDelete }}>
//..
</PostContext.Provider>
);
};
and from your components :
const PostCard = ({ item }) => {
const { handleDelete } = useContext(PostContext); // you have to import it from App
return (
<div onClick={() => handleDelete(item.id)}>{item.title}</div>
);
};
when it is a component from which you want to navigate you just add the redirection code:
onClick={() => {
handleDelete(item.id)
// navigation
}}
learn more here about useContext