简体   繁体   中英

How can i display different component in map()

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:

reference

Make sure you return the component to be rendered inside map .

if (){ 
    return <Card / > ;
}
else {
    return <QuestionCard / > ;
}

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:

  1. isQuestion — if set to true then the card is a question;
  2. isPost — if set to true 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} />
            )
          )}

PS 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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM