3

I'm trying to generate HTML inside of the react component, but i don't know how to do it correctly. Here is my code:

import React from 'react'

const Pagination = (props) => {
  let items = []
  for (let i = 0; i <= props.pages; i++) {
    items.push(`<li class="page-item" value=${i} onClick={props.handleClick}><a class="page-link" href="/#">${i}</a></li>`)
  }
  return (
    <nav aria-label="Page navigation example" className='mb-5' style={{ overflowX: 'scroll' }} >
      <ul class="pagination ">
        <li class="page-item">
          <a class="page-link" href="/#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>

        {items}

        <li class="page-item">
          <a class="page-link" href="/#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>
  )
}

export default Pagination

In this case it just pushes a string value to the array. Is there any way to fix it ?

4
  • 1
    Remove the ` and $ characters: items.push(<li value={i} ... />) Commented Jul 28, 2019 at 21:47
  • @Chris G yes it fixed it thanks a lot Commented Jul 28, 2019 at 21:49
  • 1
    Keep in mind you are working with JSX not html within the function. Will get rendered as html but that is different and is after the function gets compiled Commented Jul 28, 2019 at 21:51
  • @Chris G if you could post your answer, i'd accept it since you answered first. Thanks Commented Jul 28, 2019 at 22:02

1 Answer 1

2

Remove the backticks ` and $, otherwise this will not be interpreted as JSX.

Also, when working with JSX you use attribute className instead of class, to avoid confusion with the JS reserved word class.

import React from 'react'

const Pagination = (props) => {
  let items = []
  for (let i = 0; i <= props.pages; i++) {
    items.push(<li className="page-item" value={i} onClick={props.handleClick}><a className="page-link" href="/#">{i}</a></li>);
  }
  return (
    <nav aria-label="Page navigation example" className='mb-5' style={{ overflowX: 'scroll' }} >
      <ul className="pagination ">
        <li className="page-item">
          <a className="page-link" href="/#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>

        {items}

        <li className="page-item">
          <a className="page-link" href="/#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>
  )
}

export default Pagination
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.