Is this correct way to clean input in React?

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

This way change virtual DOM or real? How right?

1 Answers

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.

Related