Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'reset' a ReactJS element?

I'm trying to 'reset' a ReactJS element.

In this case, the element is 90%+ of the contents of the page.

I'm using replaceState to replace the state of the element with with its initial state.

Unfortunately, sub-elements which have their own 'state' do not reset. In particular, form fields keep their contents.

Is there a way of forcing a re-render of an element, which will also cause sub-elements to re-render, as if the page had just loaded?

like image 557
fadedbee Avatar asked Oct 14 '14 10:10

fadedbee


People also ask

How do I reset a component in React?

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).

How do I reset a select React?

You can clear the value of react select using the ref. Just store the value in the state, and change the state programmatically using componentDidUpdate etc... Note: 'value' should be an object. A simple option would be to pass null to the value prop.

How do I reset dom in React?

For anyone looking to just reset their form fields, there is a standard DOM reset() function that will clear all the inputs in a given element.

How do you clear props value in React?

To clear the input's value, we have to set the message state variable to an empty string. The handleClick function we passed to the onClick prop of the button element gets called every time the button is clicked. The button could be your form's submit button or a simple button that triggers an event.


3 Answers

Adding a key to the element forces the element (and all its children) to be re-rendered when that key changes.

(I set the value of 'key' to simply the timestamp of when the initial data was sent.)

render: function() {
  return (
    <div key={this.state.timestamp} className="Commissioning">
      ...
like image 119
fadedbee Avatar answered Oct 16 '22 12:10

fadedbee


The this.replaceState(this.getInitialState()) method doesn't actually reset children that are inputs, if that's what you're looking for. For anyone looking to just reset their form fields, there is a standard DOM reset() function that will clear all the inputs in a given element.

So with React, it'd be something like this:

this.refs.someForm.getDOMNode().reset();

Doumentation:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset

like image 7
Chris Dolphin Avatar answered Oct 16 '22 11:10

Chris Dolphin


If it is a form you want to reset, you simply can use this

// assuming you've given {ref: 'form'} to your form element
React.findDOMNode(this.refs.form).reset();
like image 4
nonkertompf Avatar answered Oct 16 '22 11:10

nonkertompf