Clear an input field with Reactjs?

JavascriptReactjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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>

Solution 3 - Javascript

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

Solution 4 - Javascript

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'

Solution 5 - Javascript

You can use input type="reset"

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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>

Solution 8 - Javascript

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 = '';

 

Solution 9 - Javascript

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.

Solution 10 - Javascript

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason ChenView Question on Stackoverflow
Solution 1 - JavascriptGaleel BhashaView Answer on Stackoverflow
Solution 2 - JavascriptSatheeshView Answer on Stackoverflow
Solution 3 - Javascriptsean le royView Answer on Stackoverflow
Solution 4 - JavascriptAveryFreemanView Answer on Stackoverflow
Solution 5 - JavascriptDương DieselView Answer on Stackoverflow
Solution 6 - JavascriptArtem VorobiovView Answer on Stackoverflow
Solution 7 - JavascriptAamir Ali HussainView Answer on Stackoverflow
Solution 8 - JavascriptJoannaView Answer on Stackoverflow
Solution 9 - Javascriptelano7View Answer on Stackoverflow
Solution 10 - JavascriptPete FullenView Answer on Stackoverflow