简体   繁体   中英

Reactjs - Multiple if conditions inside map function

I am trying to add a progress bar with different colors levels at different values. I have 4 different value option. I am trying to use if/ else if conditions for a particular case but not working. Is there any better approach.

<ul className="venue-list">
      {searchVenues.map(item => (
        <li className="venue-list__item" key={item.venue.id}>
          <Link
            to={`/venues/${item.venue.id}`}
            className="venue-list__itemLink"
          >
            <div className="venue-list__cover" />
            <img
              src={`${item.venue.photos.groups[0].items[0].prefix}128${item.venue.photos.groups[0].items[0].suffix}`}
              alt="Venue Best Img"
              className="venue-list__image"
            />
            <div className="venue-list__onTopData">
              <h3 className="venue-list__venue-name">{item.venue.name}</h3>
              <div className="venue-list__venueInfo">
                <div className="venue-list__userWrapper">
                  <div className="left">
                    <img src="/image/user-icon.png" alt="Icon" />
                  </div>
                  <div className="right">
                    <span className="user-text">{item.venue.stats.tipCount}</span>
                  </div>
                </div>
                <div className="venue-list__tagWrapper">
                  <div className="left">
                    <img src="/image/tag-icon.png" alt="Icon" />
                  </div>
                  <div className="right">
                    <div className="bar">
                    {
                      if(item.venue.price.tier === 1){
                        return <span className="percentage one"></span>
                      } else if(item.venue.price.tier === 2) {
                        return <span className="percentage one"></span>
                                <span className="percentage two"></span>
                      } else if(item.venue.price.tier === 3) {
                        return <span className="percentage one"></span>
                                <span className="percentage two"></span>
                                <span className="percentage three"></span>
                      } else if (item.venue.price.tier === 4) {
                        return  <span className="percentage one"></span>
                          <span className="percentage two"></span>
                          <span className="percentage three"></span>
                          <span className="percentage four"></span>
                      }
                    }

                    </div>
                  </div>
                </div>
                <div className="venue-list__ratingWrapper">
                  <img src="/image/triangle.png" alt="icon" />
                  <span className="rating-text">{item.venue.rating}</span>
                </div>
              </div>
            </div>
          </Link>
        </li>
      ))}
    </ul>

Now I am getting an error "Syntax error: Unexpected toke for if statement". Whats the best approach to handle cases in map function.

在此处输入图像描述

You can use ternary operator

<div className="bar">
                    {
                      item.venue.price.tier === 1?
                     <div> <span className="percentage one"></span></div>
                      :item.venue.price.tier === 2?
                       <div> <span className="percentage one"></span>
                              <span className="percentage two"></div></span>
                      :item.venue.price.tier === 3 ?
                        <div> <span className="percentage one"></span>
                                <span className="percentage two"></span>
                                <span className="percentage three"> 
                              </span></div>
                     :item.venue.price.tier === 4?
                        <div>  <span className="percentage one"></span>
                          <span className="percentage two"></span>
                          <span className="percentage three"></span>
                          <span className="percentage four"></span> </div>
                    :''

                }
                    </div>
{item.venue.price.tier === 1 && <span className="percentage one"></span>}

If/else statements don't work in JSX, because of how the 'language' is designed to make calls / construct objects. This is how to achieve conditional rendering.

Bear in mind also that you will also have to return just one element. So you will have to group the latter options like so:

<div>
    <span className="percentage one"></span>
    <span className="percentage two"></span>
    <span className="percentage three"></span>
    <span className="percentage four"></span>
</div>

The problem can be solved by extracting the section to a pure function that can return the set of <span> as an array. Here is a way to refactor your code:

const getPriceTier = (tier = 0) => {
    if (tier > 4) {
        console.log('Config only supports till "percentage four"');
    }

    const config = {
        0: 'one',
        1: 'two',
        2: 'three',
        3: 'four'
    };
    const items = Array.from({ length: tier }, (v, i) => i);
    // items = [0, 1, 2, tier - 1];

    return items.map((i) => {
        return <span className={`percentage ${config[i]}`}></span>
    })
}

And then in the render just use it as:

<div className="bar">{getPriceTier(item.venue.price.tier)}</div>

Hope this helps!

To simplify your example you could use something like

const Test = () => {
  const arr = [1,2,3,4]
  return (
    <div>
      {arr.map(e => {
        return (
          (e > 1) ?
          <p key={e}>this is true {e}</p>
          :
          <p key={e}>this is false {-e}</p>
        )
      })}
    </div>
  )
}

{dummyData.map((item) => { if (item.questionType === "singleselect") { return ( <> </> ); } else if (item.questionType === "multiselect") { return ( <> </> ); } return ( <> </> ); })}

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