69

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?

13 Answers 13

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
Got it. Instead of using this.refs.inputTitle.value="" I used this.inputTitle="", which did the trick.
'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)}`
Should just be this.inputTitle.value = "";. React has deprecated use of this.refs: facebook.github.io/react/docs/…
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 Comments

Coming from angular: this seems like a two-way binding approach, which I like.
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.
Jhee whizz, only solution that worked for me. Thanks.
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
21

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'

Comments

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;
}

Comments

16

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.

1 Comment

state is definitely not the best way. It is not performing. You should only cause re-renders in forms when needed, to enable / disable buttons, show validation messages or styles.
9

You can use input type="reset"

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

Comments

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 Comment

What if onChange is on <form /> tag? I don't want to add onChange on every input. How do you approach this?
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 = '';

 

Comments

1

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>

Comments

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.

Comments

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}
   />



 

Comments

0

To reset all value after submit, I often use

event.currentTarget.reset()

in function handleSubmit(event: FormEvent) after utilizing the value getting from the form

Comments

-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 Comments

Why are you not just using ref instead of id + document.getElementById ? I do not see this as an improvement to the accepted answer
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.