'How to architecture React event handler
I have a list of items, each of which is represented by a component and supports a couple of actions such as "Like", "Save", I have 2 options: one is to keep the handlers in list(Parent) component and pass the handlers to each item component or I can have the handlers in the item component, the code may look like below, I am wondering which one is better, Thanks!
Solution 1:
const ItemComp = ({item, onLike, onSave}) => {
return (
<>
<p>{item.name}</p>
<div>
<button onClick={() => onLike(item.id)}>Like</button>
<button onClick={() => onSave(item.id)}>Save</button>
</div>
</>
)
}
const ListComp = ({items}) => {
const handleLike = (id) => {
console.log(id)
// like it
}
const handleSave = (id) => {
console.log(id)
// save it
}
return (
{items.map(
(item) => {
return <ItemComp item={item} onLike={handleLike} onSave={handleSave} >
}
)}
)
}
<List items={items} />
Solution 2:
const ItemComp = ({item}) => {
// keep event handlers inside of child component
const handleLike = (id) => {
console.log(id)
// like it
}
const handleSave = (id) => {
console.log(id)
// save it
}
return (
<>
<p>{item.name}</p>
<div>
<button onClick={() => handleLike(item.id)}>Like</button>
<button onClick={() => handleSave(item.id)}>Save</button>
</div>
</>
)
}
const ListComp = ({items}) => {
return (
{items.map(
(item) => {
return <ItemComp item={item} >
}
)}
)
}
<List items={items} />
Solution 1:[1]
if you are going to use the component in the same context throughout the whole app, or write an explanatory document for your components, its better if the handlers are inside. Otherwise, you would have to write new handlers for each time you use the component.
Think of it as a UI Library. Pass the data, see the result :)
BUT,
if you are going to use the component as a general, container kind of component, you'll have to write the handlers outside, because the component's own handlers wouldn't know how to handle the different kind of data if you introduce new contexts for it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Berkay G. |