I have a Card
component and a QuestionCard
component.
what I want to do is when a user uploads a post or asks a question, it shows the respective component. And this is my idea of doing it :
const CardList = ({cardList}) => {
return (
<div className="cardWrapper">
<div className="cardColumn">
{cardList.map((card)=>{
if(){
<Card />
} else{
<QuestionCard />
}
})}
</div>
but I don't know what to fill in the expression. Am I have the right idea? Or there are some other ways to do it?
Here is some reference how what it should look like:
CodePudding user response:
Make sure you return the component to be rendered inside map
.
if (){
return <Card / > ;
}
else {
return <QuestionCard / > ;
}
CodePudding user response:
If I understand correctly:
- If a question is asked by the user — we wish to render
<QuestionCard />
; - If a post is uploaded by the user — we wish to render
<Card />
.
First off, you need a way to determine if the looped-over object is a question or a post:
One way of doing so is adding 1 or 2 boolean
properties to your cardList
array of objects:
isQuestion
— if set totrue
then the card is a question;isPost
— if set totrue
then the card is an uploaded post.
In fact, one of the two is plenty enough for this use case.
card.isQuestion ? (Render <QuestionCard/>) : (Render <Card />)
I am using a ternary operator because it is easier to read than an if
statement.
Provided that's what you want to do, your test would look like this:
{cardList.map((card, id) =>
card.isPost ? ( // Render <Card /> if the card is a post
<Card key={id} />
) : ( // If the card isn't an uploaded post then it is necessarily a question
<QuestionCard key={id} />
)
)}
P.S. You should probably use NextJS' dynamic styling system depending on how much your project is going to scale, to avoid any mix-ups between the same classname in different files in the future.
``