Remove rendered data from UI

Viewed 44

I have a component that prints 10 numbers one after another. I also have a button Clean that have to remove this 10 numbers when it's clicked. I am not sure how to implement it.

import { useState } from 'react'

export default function Timeout() {
  const [message, setMessage] = useState([1])
  const Markup = (
    <ul>
      {message?.map((n) => (
        <li>{n}</li>
      ))}
    </ul>
  )
  setTimeout(() => {
    if (message.length <= 9) {
      setMessage([...message, message[message.length - 1] + 1])
    }
  }, 1000)

  return (
    <div>
      <button>Clean</button>
      <div>{Markup}</div>
    </div>
  )
}

If I add <button onClick={setMessage([])>Clean</button> I get Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

1 Answers

onClick takes in a function. Setting onClick to an arrow function should fix the infinite loop.

<button onClick={()=>setMessage([])}> Clean </button>
Related