0

Related to this question, I have some items and I want to iterate them in React js. Here is my items and component:

const itemlists = [
  {
    "id": 1,
    "url": "/one",
    "title": "One",
    "category": "News"
  },
  {
    "id": 2,
    "url": "/two",
    "title": "Two",
    "category": "News"
  },
  {
    "id": 3,
    "url": "/three",
    "title": "Three",
    "category": "News"
  },
  {
    "id": 4,
    "url": "/four",
    "title": "Four",
    "category": "News"
  },
  {
    "id": 5,
    "url": "/five",
    "title": "Five",
    "category": "News"
  },
  {
    "id": 6,
    "url": "/six",
    "title": "Six",
    "category": "News"
  }
]

Cards component

class Cards extends Component {
    render() {
        const renderData = itemlists.map((item, i) => {
            return (
                <div className="card-row" key={i}>

                    <div className="card-content">
                        <div className="card-left">

                            // This should be 2 items in left side
                            <div className="item">{item.title}</div>

                        </div>
                        <div className="card-right">

                            // This should be 4 items in right side
                            <div className="item">{item.title}</div>

                        </div>
                    </div>

                    <div className="pagination">
                        <a href={item.url}>More in {item.category}</a>
                    </div>

                </div>
            )
        })
        return (
            <Fragment>
                {renderData}
            </Fragment>
        );
    }
}

I got parsing error when I put if else statement within return, for example:

<div className="card-left">
    {
      ---- this if statement gives error ----
      if((items + 1) % 3 === 0) {
        ....
      }
    }
    <div className="item">{item.title}</div>
</div>

My goal is to split those items into two groups (2 in left side and 4 in right side). I Also want to put pagination link below in <div className="pagination">. I have been confusing in logic. Let me know if there was simple way to achive my goal.

Regards.

mrale81
  • 169
  • 3
  • 15

2 Answers2

3

Instead of an if-else statement use a ternary operator like:

(items + 1) % 3 === 0 ? doThis() : doThat()
sertsedat
  • 3,490
  • 1
  • 25
  • 45
Anton Harniakou
  • 855
  • 6
  • 13
0

As per the documentation

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

So instead of if you need to use ternary operator.
Example of ternary operator is as follows

<div className="card-left">
    {
         (items + 1) % 3 === 0 ? Task1 : Task2 

    }
    <div className="item">{item.title}</div>
</div>
Harikrishnan
  • 1,097
  • 8
  • 13