'React components when to write logics into component and when to write them in their parents?
Here is my component:
export default function Card({ title, myFunc }) {
return (
<div>
<h2>{title}</h2>
<button onClick={myFunc}>click to add</button>
</div>
);
}
and here is my app (its parent) where I used it:
function App() {
return (
<div className="App">
{data.map((item) => {
return (
<Card
key={item.id}
title={item.title}
myFunc={() => {
alert('hi');
}}
/>
);
})}
</div>
);
}
As it can be seen I implemented the logic,which shows 'hi' by clicking on the button, outside my component. This is while I could have implemented the above logic just inside my component to do the same thing without any change in my app code just like this:
export default function Card({ title }) {
return (
<div>
<h2>{title}</h2>
<button
onClick={() => {
alert('hi');
}}
>
click to add
</button>
</div>
);
}
What I'm trying to figure out is when should I implement my logic inside the component and when outside it? Is there any rules or something about it or it does not matter at all?
Solution 1:[1]
If Parent need information for working and Child update this information, you must place information and function in Parent and give a callback function to the Child. If an other Child of Parent need the value update by an another Child, you must create value and function in Parent, and give value and callback to Child.
Else, if Parent don't care about the Child to do and the value is manipulate, Child be work alone.
In you're example, Child need title from Parent because Parent have the Array with title so clearly, it's normal usage. But the function alert('hi') can be directly on your child, because every Card do the same things and Parent don't care about what happen after alert('hi').
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 |
