Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reset the defaultValue for a React input

Tags:

reactjs

I have a set of React input elements that have a defaultValue set. The values are updated with an onBlur event.

I also have another action on the page that updates all values in these input elements. Is there a way to force react to render the new defaulValues when this happens?

I can't easily use onChange since it would trigger a premature rerender (The inputs contain a display order value and a premature rerender would move them).

I could create a duplicate state, one for the real values that is only updated with onBlur and one to update the value in the input element while it is being edited. This would be far from ideal. It would be so much simpler to just reset the default values.

like image 955
SystemicPlural Avatar asked Jun 21 '16 13:06

SystemicPlural


People also ask

How do you set a default value for an uncontrolled field?

We can set a default value for an uncontrolled form field by using the defaultValue property.

How do I reset my React data?

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' }) ).


1 Answers

As mentioned in https://stackoverflow.com/a/21750576/275501, you can assign a key to the outer element of your rendered component, controlled by state. This means you have a "switch" to completely reset the component because React considers a new key to indicate an entirely new element.

e.g.

class MyComponent extends React.Component {
  
  constructor() {
  
    super();
    this.state = { 
    
      key: Date.now(),
      counter: 0
      
    };
    
  }
  
  updateCounter() {
  
    this.setState( { counter: this.state.counter + 1 } );
    
  }
  
  updateCounterAndReset() {
  
    this.updateCounter();
    this.setState( { key: Date.now() } );
    
  }
  
  render() { return ( 
  
    <div key={this.state.key}>
  
      <p>
      
        Input with default value:
        <input type="text" defaultValue={Date.now()} />
     
      </p>

      <p>
        Counter: {this.state.counter}
        <button onClick={this.updateCounter.bind( this )}>Update counter</button>
        <button onClick={this.updateCounterAndReset.bind( this )}>Update counter AND reset component</button>
        
      </p>
      
    </div>
  
  ); }
  
}

ReactDOM.render( <MyComponent />, document.querySelector( "#container" ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container" />
like image 134
goofballLogic Avatar answered Oct 20 '22 02:10

goofballLogic