0

I am using React and I am getting the following error: TypeError: Cannot set property 'innerHTML' of null. I did see some questions related to this error but I did not find any that helped me.

//React
class Pagination extends Component {

  pagincationScript = (totalPages, page) =>{
    const ulTag = document.querySelector("ul");

    let liTag = '';
    if(page > 1){
      liTag = `<li className="Btn Previous"><span><i>&#8592;</i>Previous</span></li>`
    }

ulTag.innerHTML = liTag;

  }

  render() {

    return (
      <div className="Pagination">
        <ul>

        {this.pagincationScript(10, 5)}

        </ul>
      </div>
    )
  }
}

export default Pagination;
5
  • 1
    In general, if you're using document.querySelector you're not using React the right way. Can you explain more about what you're trying to do and what your markup looks like? Commented Jan 12, 2021 at 4:19
  • 1
    Adding html manually like this in react is not the right way Commented Jan 12, 2021 at 4:21
  • Its just a <ul> tag as shown in the question within render(). I hope I answered your question Commented Jan 12, 2021 at 4:23
  • @jmargolisvt so basically for my school project I am building a basic pagination component that displays 20 rows of data per page. I am grabbing the tags using document.querySelector. Commented Jan 12, 2021 at 4:36
  • 1
    Does this answer your question? How to loop in react Commented Jan 12, 2021 at 4:41

1 Answer 1

2

When writing React you should always be writing JSX, like in the render function you wrote. To render the <li> separately you can do something like the following:

function Li() {
  return (
    <li className="Btn Previous"><span><i>&#8592;</i>Previous</span></li>
  )
}

export default function Pagination() {
  // Loop as many times as needed
  const lis = [];
  for (let i = 0; i < 10; i++) {
    lis.push(<Li key={i} />);
  }

  return (
    <div className="Pagination">
      <ul>
        {lis}
      </ul>
    </div>
  )
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I did that and it works perfectly fine but I want to loop a certain amount of time to display the <li> tags. How can I use the for loop with the approach you mentioned above?
I added an example of looping 10 times, creating 10 <Li> elements.
Thank you so much! Dont know why people are so quick to give a down vote. I am still learning. But thank you so much. Your post helped and may you continue to help others like you helped me.

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.