66

I am using a variable below.

var newInput = {
   title: this.inputTitle.value,
   entry: this.inputEntry.value    
};

This is used by my input fields.

<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />   
<textarea id="inputage" ref={el => this.inputEntry = el} className="form-control" />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>

Once I activate {this.sendthru} I want to clear my input fields. However, I am uncertain how to do so.

Also, as shown in this example, it was pointed out to me that I should use the ref property for input values. What I am unclear of is what exactly does it mean to have {el => this.inputEntry = el}. What is the significance of el in this situation?

12 Answers 12

53

Let me assume that you have done the 'this' binding of 'sendThru' function.

The below functions clears the input fields when the method is triggered.

sendThru() {
    this.inputTitle.value = "";
    this.inputEntry.value = "";
}

Refs can be written as inline function expression:

ref={el => this.inputTitle = el}

where el refers to the component.

When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.

Read more about it here.

4
  • Could you expand a bit on what you mean by 'this' binding of sendthru function? As is, when I click I get an error of cannot read property value of undefined
    – Jason Chen
    Aug 3, 2016 at 0:32
  • Got it. Instead of using this.refs.inputTitle.value="" I used this.inputTitle="", which did the trick.
    – Jason Chen
    Aug 3, 2016 at 0:44
  • 1
    'sendThru' is a event handler for onClick function, React recommends to bind 'this' reference at your constructor method. example constructor() { this.sendThru = this.sendThru.bind(this)}' or if you are not using ES6 classes for react component you could bind the this key word in your render method as onClick={this.sendThru.bind(this)}` Aug 6, 2016 at 14:44
  • 1
    Should just be this.inputTitle.value = "";. React has deprecated use of this.refs: facebook.github.io/react/docs/…
    – Jeff
    Aug 30, 2017 at 0:28
35

Declare value attribute for input tag (i.e value= {this.state.name}) and if you want to clear this input value you have to use this.setState({name : ''})

PFB working code for your reference :

<script type="text/babel">
    var StateComponent = React.createClass({
        resetName : function(event){
            this.setState({
                name : ''
            });
        },
        render : function(){
            return (
                <div>
                    <input type="text" value= {this.state.name}/>
                    <button onClick={this.resetName}>Reset</button>
                </div>
            )
        }
    });
    ReactDOM.render(<StateComponent/>, document.getElementById('app'));
</script>
4
  • 1
    Coming from angular: this seems like a two-way binding approach, which I like. Mar 12, 2018 at 2:14
  • 5
    This only works if you also add logic to update this.state.name whenever there are key presses in the input. Otherwise it is frozen to '', the initial value of 'this.state.name. Feb 27, 2019 at 18:06
  • Jhee whizz, only solution that worked for me. Thanks. Sep 17, 2020 at 20:56
  • you don't always want this, every state change causes a rerender, and sometimes that is exactly what you want, but sometimes you want to be more specific
    – Tosh
    Sep 21, 2021 at 18:51
19

I'm not really sure of the syntax {el => this.inputEntry = el}, but when clearing an input field you assign a ref like you mentioned.

<input type="text" ref="someName" />

Then in the onClick function after you've finished using the input value, just use...

this.refs.someName.value = '';

Edit

Actually the {el => this.inputEntry = el} is the same as this I believe. Maybe someone can correct me. The value for el must be getting passed in from somewhere, to act as the reference.

function (el) {
    this.inputEntry = el;
}
19

I have a similar solution to @Satheesh using React hooks:

State initialization:

const [enteredText, setEnteredText] = useState(''); 

Input tag:

<input type="text" value={enteredText}  (event handler, classNames, etc.) />

Inside the event handler function, after updating the object with data from input form, call:

setEnteredText('');

Note: This is described as 'two-way binding'

1
  • perfect solution when using React, thanks
    – Speedy11
    Jan 21 at 6:54
10

Now you can use the useRef hook to get some magic if you do not want to use the useState hook:

function MyComponent() {
  const inputRef = useRef(null);
  const onButtonClick = () => {
    // @ts-ignore (us this comment if typescript raises an error)
    inputRef.current.value = "";
  };
  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={onButtonClick}>Clear input</button>
    </>
  );
}

As I mentioned, if you are using useState that is the best way. I wanted to show you also this special approach.

8

You can use input type="reset"

<form action="/action_page.php">
  text: <input type="text" name="email" /><br />  
  <input type="reset" defaultValue="Reset" />  
</form>
0
2

Also after React v 16.8+ you have an ability to use hooks

import React, {useState} from 'react';

const ControlledInputs = () => {
  const [firstName, setFirstName] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log('firstName :>> ', firstName);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
          <label htmlFor="firstName">Name: </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        <button type="submit">add person</button>
      </form>
    </>
  );
};
1
  • 1
    What if onChange is on <form /> tag? I don't want to add onChange on every input. How do you approach this?
    – aldoblack
    Jul 23, 2021 at 17:53
2

You can use useState:

import React, { useState } from 'react';
const [inputTitle, setInputTitle] = useState('');

then add value to your input component:

render() {
<input type="text" onChange={(e) => setInputTitle(e.target.value)} 
value={inputTitle} />
<button onClick={handleSubmit} type="submit">Submit</button>
}

On your submit handler function:

setInputTitle('');
 document.querySelector('input').defaultValue = '';

 
1

I used the defaultValue property, useRef, and onClick to achieve this.

let ref = useRef()

and then inside the return:

<input type="text" defaultValue="bacon" ref={ref} onClick={() => ref.current.value = ""} />

also if you want to use onChange for the input it wouldn't require any more configuration and you can just use it. If you want to have a dynamic defaultValue then you absolutely can, with useState.

0

On the event of onClick

this.state={
  title:''
}

sendthru=()=>{
  document.getElementByid('inputname').value = '';
  this.setState({
     title:''
})
}
<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />   
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
0

A simple way to reset the input in React is by implementing the onBlur inside the input.

onBlur={cleanSearch}

ej:

const [search, setSearch] = useState('')

const handleSearch = ({target}) =>{
    setSearch(target.value)
}



const cleanSearch = () =>setSearch('')


 <input
       placeholder="Search…"
       inputProps={{ 'aria-label': 'search' }}
       value={search}
       onChange={handleSearch}
       onBlur={cleanSearch}
   />



 
-6

The way I cleared my form input values was to add an id to my form tag. Then when I handleSubmit I call this.clearForm()

In the clearForm function I then use document.getElementById("myForm").reset();

import React, {Component } from 'react';
import './App.css';
import Button from './components/Button';
import Input from './components/Input';

class App extends Component {  
  state = {
    item: "", 
    list: []
}

componentDidMount() {
    this.clearForm();
  }

handleFormSubmit = event => {
   this.clearForm()
   event.preventDefault()
   const item = this.state.item

    this.setState ({
        list: [...this.state.list, item],
            })

}

handleInputChange = event => {
  this.setState ({
    item: event.target.value 
  })
}

clearForm = () => {
  document.getElementById("myForm").reset(); 
  this.setState({
    item: ""
  })
}



  render() {
    return (
      <form id="myForm">
      <Input

           name="textinfo"
           onChange={this.handleInputChange}
           value={this.state.item}
      />
      <Button
        onClick={this.handleFormSubmit}
      >  </Button>
      </form>
    );
  }
}

export default App;
2
  • Why are you not just using ref instead of id + document.getElementById ? I do not see this as an improvement to the accepted answer
    – the_cheff
    May 17, 2018 at 22:02
  • 2
    Playing devil's advocate, the ref system was introduced three weeks after this answer, on 16.3, so maybe he didn't knew a better method. But I agree that needs to be updated.
    – Checo R
    Sep 24, 2019 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.