How to reset a React element?

Sometimes, we want to reset a React element.

In this article, we’ll look at how to reset a React element.

How to reset a React element?

To reset a React element, we can change the value of the key prop of the element.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [key, setKey] = useState();

  return (
    <div>
      <button onClick={() => setKey(Math.random())}>reload</button>
      <div key={key}>{Math.random()}</div>
    </div>
  );
}

We define the key state with the useState hook.

Then we add a button with the onClick prop set to a function that calls setKey with a random number.

Next, we assign the key state as the value of the key prop.

As a result, we should see the random number in the div change when we click on the button.

Conclusion

To reset a React element, we can change the value of the key prop of the element.