I have a component called a Card. I render it twice on page 1 and page 2 and it displays somewhat different content depending on the page . Here is my initial approach.
const Card = () => {
const [cardState, setCardState] = useState("firstpage");
const firstPageProducts = productArray.slice(0, 4);
const secondPageProducts = productArray.slice(5, productArray.length);
const [shownImages, setshownImages] = useState([]);
useEffect(() => {
const shownImages = firstPageProducts.slice(0, 2);
setshownImages(shownImages);
}, []);
if (cardState === "firstpage") {
return (
<div>
some first page stuff
</div>
);
} else if (cardState === "secondpage") {
return (
<div>
some second page stuff
</div>
);
}
};
I want it to have a way for it to be stateless in a way that I can define from the page in which I'm rendering the card state. I also want it to persist in that if I go back to page 1 it loads correctly page 1 stuff.
right now if I pass down the card state as a prop to the app it sometimes throws an error claiming that the component has not been rendered at all or if it does it changes both the first-page component and the second-page component. I'm fairly new to react and I've heard of stateless components. I was thinking this has the potential to be one of them.
How can I achieve this?
I think what you want is prop. Prop is something passed to child component
in your case Card
from parent component like a Deck
component or something. Idk if that exist in your app.
eg
const Deck = () => {
return (
<div>
<Card cardContent='I am first' productList={[1, 2, 3]} />
<Card cardContent='I am second' productList={[4, 5, 6]} />
</div>
);
};
const Card = ({ cardContent, productList }) => {
return <div>
<h1>{cardContent}</h1>
{productList.map((product) => {
return <p>{product}</p>
})}
</div>;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.