user1177860 user1177860 - 2 months ago 38
React JSX Question

reseting or clearing an input field with reactjs

I having the following problem.

I have a react component which does a filter search on a list which is fine, but I want to clear the input field with a button, if i add a value attribute to the input field which I can set in the setState but then it stops the onChange from working as it does the filter search on the list:

I've created the following but this still doesn't work.

<input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick="React.findDOMNode(this.refs.form).reset()"><i className="uk-icon-undo"></i></button>

Answer

set the value to empty as

handleClick = () => {
        ReactDOM.findDOMNode(this.refs.form).value = "";
      }

and yes onClick expects a function or a value not a string. Also React.findDOMNode() is deprecated. You should use ReactDOM.findDOMNode();

  
class Hello extends React.Component {
  handleChange = (e) => {
  
  }
  handleClick = () => {
    ReactDOM.findDOMNode(this.refs.form).value = "";
  }
  render() {
    
    return (
      <div>
      <input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick={this.handleClick}><i className="uk-icon-undo"></i>click</button>
      </div>
    )
  }
}

ReactDOM.render(<Hello />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>

Also Its a better idea to use state and change the state for input value.

as

class Hello extends React.Component {
  constructor() {
    super() 
      this.state = {
        valueAttr : ''
      
    }
  }
  handleChange = (e) => {
    this.setState({valueAttr: e.target.value});
  }
  handleClick = () => {
    this.setState({valueAttr: ''})
  }
  render() {
    
    return (
      <div>
      <input type="text" ref="form" placeholder="Search indicators" className="uk-width-1-1" value = {this.state.valueAttr} onChange={this.handleChange} />

<button className="uk-button uk-width-1-1" onClick={this.handleClick}><i className="uk-icon-undo"></i>click</button>
      </div>
    )
  }
}

ReactDOM.render(<Hello />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>

I personally prefer the second approach. But you can do it in whichever way you feel comfortable.