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?

Wonjun Kim
  • 61
  • 10
Jason Chen
  • 2,487
  • 5
  • 25
  • 44

12 Answers12

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.

John Weisz
  • 30,137
  • 13
  • 89
  • 132
Galeel Bhasha
  • 1,877
  • 13
  • 19
  • 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 03 '16 at 00:32
  • Got it. Instead of using `this.refs.inputTitle.value=""` I used `this.inputTitle=""`, which did the trick. – Jason Chen Aug 03 '16 at 00: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)}` – Galeel Bhasha Aug 06 '16 at 14:44
  • 1
    Should just be ``this.inputTitle.value = "";``. React has deprecated use of ``this.refs``: https://facebook.github.io/react/docs/refs-and-the-dom.html#legacy-api-string-refs – Jeff Aug 30 '17 at 00: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>
Diptendu Das
  • 3,990
  • 7
  • 22
  • 38
Satheesh
  • 351
  • 3
  • 2
  • 1
    Coming from angular: this seems like a two-way binding approach, which I like. – Mitch Wilkins Mar 12 '18 at 02: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`. – evanrmurphy Feb 27 '19 at 18:06
  • Jhee whizz, only solution that worked for me. Thanks. – KylianMbappe Sep 17 '20 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 '21 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;
}
sean le roy
  • 571
  • 1
  • 7
  • 19
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'

Batman
  • 5,563
  • 18
  • 79
  • 155
AveryFreeman
  • 1,061
  • 2
  • 14
  • 23
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.

elano7
  • 1,584
  • 1
  • 18
  • 18
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>
Dương Diesel
  • 112
  • 1
  • 2
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>
    </>
  );
};
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 = '';

 
Joanna
  • 29
  • 2
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>
Aamir
  • 152
  • 6
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}
   />



 
cesarG24
  • 11
  • 3
-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;
  • 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 '18 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 '19 at 22:53