Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i generate HTML in React functional component?

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 ?

like image 245
Noob Avatar asked Dec 08 '25 09:12

Noob


1 Answers

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
like image 52
Guilherme Lemmi Avatar answered Dec 10 '25 21:12

Guilherme Lemmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!