3
<input
  id='block-input'
  type='text' 
  ref={(input) => {this.blockInput = input;}} />
this.blockInput.value = '';

This way change virtual DOM or real? How right?

1 Answers1

7

What you're doing is not recommended.

It's better if you make a controlled input. To achieve that, you have to:

  • Provide a state for the input's value

  • Handler function to handle the change of the input. So, everytime the input is changed, it will update the state.

For example:

App.js

class App extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
        name: ''
    }
  }
  handleChange = event => {
    this.setState({ 
        name: event.target.value
    });
  }
  resetInput = () => {
    this.setState({ name: '' });
  }
  render() {
    const { name } = this.state;
    return (
        <div>
            <input type="text" value={name} onChange={this.handleChange} />
            <p>Hello, {name}</p>
            <button onClick={this.resetInput}>Reset</button>
        </div>
    );
  }
}

Here is the simple snippet I made for you.

asubanovsky
  • 1,608
  • 3
  • 19
  • 36
  • In some answers i see use ref construction for this. [ex](https://stackoverflow.com/questions/38731271/clear-an-input-field-with-reactjs) Why some people use this? – Aleksandr Maybach Nov 08 '17 at 04:44
  • @AleksandrMaybach [The docs](https://reactjs.org/docs/glossary.html#refs) say it better than I could: You use a ref whenever you want to access the underlying DOM element or class instance (depending on the type of element). Programmatically focusing an input element is one example of how you could use a ref. – chipit24 Nov 08 '17 at 05:02
  • @chipit24: yes, i know. Does ref works with real or virtual DOM in this case? – Aleksandr Maybach Nov 08 '17 at 05:33
  • Formalities perhaps, but uncontrolled components are still a React way - just not the recommended approach. Perhaps that sentence should be rephrased. – Chris Nov 08 '17 at 08:20