Imagine that I have a List of Cards on my react application. So I will have two components, the <ListCard /> and <Card />.
My doubt is that where I work, when we have something like this, we usually declare a variable inside the <ListCard /> named Card that receives a JSX, but I don't know if this is a good thing to do. Recently I faced some problems with this approach, but I didn't find anyone saying to do it or not.
Imagine that I'm not using the <Card /> anywhere in the application
The way we would declare the ListCard
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
const Card = ({ title }) => <div>{title}</div>;
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
I want to know if it's better to declare outside of the ListCard, like this.
const Card = ({ title }) => <div>{title}</div>;
const ListCard = () => {
const cards = [
{ title: '1', id: 1 },
{ title: '2', id: 2 },
];
return (
<div>
<h1>List of Cards</h1>
{cards.map(card => (
<Card title={card.title} key={card.id} />
))}
</div>
);
};
It is totally fine to declare another Component in the same file, but declaring it inside another one's function would be inefficient. Imagine your app 'recreating' the second Component during each render.
So, feel free to declare it in the same file, but don't do it inside another Component's function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With