Clear an input field with Reactjs? - javascript

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?

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.

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>

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

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'

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

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.

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

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

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>

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.

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

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;

Related

How to pass a value in a form OnPost method React

const afterSubmission = (e, message) => {
e.preventDefault()
console.log(message);
if (message === "") return
displayMessage(message)
messageInput.value=""
}
<div id="message-container"></div>
<form onSubmit = {afterSubmission}>
<label for="message-input">Message</label>
<input type="text" id="message-input" />
<button type="submit" id="send-button">Send</button>
</form>
I have these two pieces of code, my question is how can I pass the value from the input tag in the form to the afterSubmission method?
Assuming this is the same component, an easy solution would be to use state.
Your code snippets aren't very useful, just as an FYI for future questions, but here's an example of me tracking form state.
import { useState } from "react";
export default function App() {
const [message, setMessage] = useState("test");
const handleChange = (e) => {
setMessage((old) => e.target.value);
};
const afterSubmission = (e) => {
e.preventDefault();
console.log(message);
};
return (
<div className="App">
<form onSubmit={afterSubmission}>
<input
type="text"
id="message-input"
value={message}
onChange={handleChange}
/>
<button
type="submit"
id="send-button"
>
Send
</button>
</form>
</div>
);
}
As you can see, this tracks your message in the component's state which makes it accessible in the afterSubmission function.

using useRef in input to avoid re render in appication

I want to implement useRef so that the component in which my input tag is should not re-render on value change. If we use useState it will re-render the entire component on every key pressed.
This is how we usually do it but this will re-render the entire component on every change.
const [name, setName] = useState('');
return(
<input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
)
I want to do this using useRef to avoid it
const name = useRef("");
const handleName = (e) => {
name.current = e.target.value
};
return(
<input type="text" placeholder="Name" value={name.current.value} onChange={handleName} />
)
but it's not working for some reason?
Change your input tag to this (inside JSX):
<input type="text" placeholder="Name" ref={name} onChange={handleName} />
Instead of value={name.current.value} use ref={name}. It should fix the issue.
Full code :
import { useRef } from "react";
export default function App() {
const name = useRef('');
const handleName = (e) => {
name.current = e.target.value
document.getElementById('test').innerText = name.current
};
return(
<>
<input type="text" placeholder="Name" ref={name} onChange={handleName} />
<p id='test'></p>
</>
)
}
if you want to avoid rendering on change, you can just pass ref to the input element. and whenever required you can get the value from ref as used in the handleSubmit method below. Html input element will maintain its state:
const nameRef = useRef(null);
const handleSubmit = () => {
console.log(nameRef.current.value);
};
return(
<input type="text" ref={nameRef} placeholder="Name" />
)

Is this a good practice in using the useState hook in a component to pass values to the parent of the component?

I am trying to create an Input component that can be used dynamically in any page which stores the input value and has an attribute getValue which lets the parent of the component access it. In App.js I have an object called "info" that stores the values taken from the Input component. Is the following code a good implementation for this problem?
Input.js
const Input = ({placeholder, getValue}) => (
<input
placeholder={placeholder}
onChange={({target}) => getValue(target.placeholder, target.value)}
/>
)
Input.defaultProps = {
getValue: (key, value) => {}
}
export default Input;
App.js
import { useState } from "react";
import Input from "./Input.js";
const App = () => {
const [info, setInfo] = useState({});
const addToInfo = (name, val) => {
let keyWord = (name.charAt(0).toLowerCase() + name.slice(1)).replace(/\s/g, "");
setInfo(prev => ({...prev, [keyWord]: val}))
}
return (
<div>
<h1>Hello {info.firstName && info.firstName} {info.lastName && info.lastName}</h1>
<Input placeholder="First Name" getValue={(name, val) => addToInfo(name, val)}/>
<br/>
<Input placeholder="Last Name" getValue={(name, val) => addToInfo(name, val)}/>
<br/>
<Input placeholder="Email" getValue={(name, val) => addToInfo(name, val)}/>
<br/>
<Input placeholder="Phone Number" getValue={(name, val) => addToInfo(name, val)}/>
<br/>
<button onClick={() => console.log(info)}>Console Log the Info</button>
</div>
);
}
export default App;
I recommend you can take a look at Formik, their approach is exactly the solution to your problem, namely, passing value up to a parent, here's the basic structure they use:
<Formik>
{(props) => (
<Form> // This is from Formik
// your basic form stuff
</Form>
)}
</Formik>
On how to make the <Form></Form> reusable, last time I asked one of their contributor on it, feel free to take a look: Make Formik a custom component
This is Formik official website
Hope this can help you draw some inspiration!

How to reset input field from useRef in React?

I have a text input. If I click on a specific button in the page, I want to reset the value of the input. Here is my code:
const inputRef = useRef()
const handleClick= () => {
inputRef.current.value.reset();
return "hello world"
}
return (
<>
<input type="text" ref={inputRef}/>
<button onClick={()=> handleClick}>delete all</button>
</>
)
It doesn't work. How to fix this?
reset is available on form element.
You can wrap your input with a form, and trigger reset on it.
const {useRef} = React;
const App = () => {
const formRef = useRef();
const handleClick = () => {
formRef.current.reset();
};
return (
<form ref={formRef}>
<input type="text" />
<input type="password" />
<input type="checkbox" />
<textarea></textarea>
<button onClick={handleClick} type="button">
clear form
</button>
</form>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can clear the value in the input field like below.
const handleClick= () => {
inputRef.current.value = "";
return "hello world"
}
and change onClick call in the button like below
onClick={handleClick}
//or
onClick={()=> handleClick()}
If you want complete reset of a form having multiple inputs, you can follow the below approach.
In below example, form will reset after submit
const formRef = useRef();
const handleClick = () => {
formRef.current.reset();
}
render() {
return (
<form ref={formRef}>
<input />
<input />
...
<input />
</form>
);
}
if you don't want to use Ref
const handleSubmit = e => {
e.preventDefault();
e.target.reset();
}
<form onSubmit={handleSubmit}>
...
</form>
You can clear the text input field by setting its value to an empty string. You can do that like this inputref.current.value = "" if you want to use uncontrolled inputs.
However, if you want to use controlled inputs you can create a state variable to track the value of the input field. For example,
const SomeComponent = () => {
const [text, setText] = useState('')
return (
<>
<input type="text" value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setText('')}>delete all</button>
</>
);
};
Here is a codesandbox with both implementation.
You have two problems, one you are passing a function that calls a function into your onClick handler -- which isn't needed. If you define the function before your render, you do not need to pass an anonymous function to the onClick handler.
// Before
<button onClick={()=> handleClick}>delete all</button>
// After
<button onClick={handleClick}>delete all</button>
The other problem is that your handleClick function calls reset, which is not a function on an input. To reset the value of the referenced input, you can set it to an empty string (or whatever you want the "default" value to be).
const handleClick = e => {
inputRef.current.value = "";
return "hello world";
};
rest value in input
import { useRef } from 'react'
const Test = () => {
const testRef = useRef(null)
return (
<div>
<input type="text" ref={testRef} />
<button onClick={() => inputSearch.current.value = ''}>×</button>
</div>
)
}
export default Test

react-bootstrap: clear element value

I'm trying to clear my input fields after an onClick event.
I'm using react-bootstrap library and while there is a getValue() method, there is not setValue(value) method.
I've stumbled upon this discussion .
I did not fully understand what they are suggesting in order to simply clean a form after submission.
After all, If I would use a simple HTML <input> instead of react-bootstrap I could grab the node via element ref and set it's value to be empty string or something.
What is considered a react way to clean my react-bootstrap <Input /> element?
Store the state in your React component, set the element value via props, get the element value via event callbacks. Here is an example:
Here is an example taken directly from their documentation. I just added a clearInput() method to show you you can clear the input by just updating the state of your component. This will trigger a re-render which will cause the input value to update.
const ExampleInput = React.createClass({
getInitialState() {
return {
value: ''
};
},
validationState() {
let length = this.state.value.length;
if (length > 10) return 'success';
else if (length > 5) return 'warning';
else if (length > 0) return 'error';
},
handleChange() {
// This could also be done using ReactLink:
// http://facebook.github.io/react/docs/two-way-binding-helpers.html
this.setState({
value: this.refs.input.getValue()
});
},
// Example of how you can clear the input by just updating your state
clearInput() {
this.setState({ value: "" });
},
render() {
return (
<Input
type="text"
value={this.state.value}
placeholder="Enter text"
label="Working example with validation"
help="Validation is based on string length."
bsStyle={this.validationState()}
hasFeedback
ref="input"
groupClassName="group-class"
labelClassName="label-class"
onChange={this.handleChange} />
);
}
});
For what I'm doing at the moment, I didn't really think it was necessary to control the Input component's value through setState/Flux (aka I didn't want to deal with all the boilerplate)...so here's a gist of what I did. Hopefully the React gods forgive me.
import React from 'react';
import { Button, Input } from 'react-bootstrap';
export class BootstrapForm extends React.Component {
constructor() {
super();
this.clearForm = this.clearForm.bind(this);
this.handleSave = this.handleSave.bind(this);
}
clearForm() {
const fields = ['firstName', 'lastName', 'email'];
fields.map(field => {
this.refs[field].refs['input'].value = '';
});
}
handleSubmit() {
// Handle submitting the form
}
render() {
return (
<div>
<form>
<div>
<Input
ref='firstName'
type='text'
label='First Name'
placeholder='Enter First Name'
/>
<Input
ref='lastName'
type='text'
label='Last Name'
placeholder='Enter Last Name'
/>
<Input
ref='email'
type='email'
label='E-Mail'
placeholder='Enter Email Address'
/>
<div>
<Button bsStyle={'success'} onClick={this.handleSubmit}>Submit</Button>
<Button onClick={this.clearForm}>Clear Form</Button>
</div>
</div>
</form>
</div>
);
}
}
If you use FormControl as an input, and you want to use ref to change/get value from it, you use inputRef instead of ref
<FormControl inputRef={input => this.inputText = input} .../>
and use this to get/change its value:
this.inputText.value
This worked for me in case someone else is looking for an answer :D
You can access the values of react-bootstrap by using
console.log(e.target.form.elements.fooBar.value)
You can clear them by using
e.target.form.elements.fooBar.value = ""
import React from 'react';
import {Button, Form} from 'react-bootstrap';
export default function Example(props) {
const handleSubmit = (e) => {
// Handle submitting the form
}
const resetSearch = (e) => {
e.preventDefault();
e.target.form.elements.fooBar.value = ""
}
render() {
return (
<Form onSubmit={handleSubmit} onReset={resetSearch} >
<Form.Control type="input" name="fooBar" />
<Button type="submit"> Submit </Button>
<Button onClick={resetSearch} type="submit" > Reset </Button>
</Form>
);
}
}
You can also just use ReactDOM:
<FormControl
componentClass="select"
ref="sStrike">
<option value="-">Select…</option>
<option value="1">1</option>
<option value="2">2</option>
</FormControl>
Now a different FormControl fires an onChange={handleChange} and in that handler you can just id the ref and set to the default value:
ReactDOM.findDOMNode(this.refs.sStrike).value = '-';
and that will set the select box to the 'default' value.
Just add a button in-side form with the attribute type="reset"
<Button variant="primary" type="reset">Reset</Button>

Categories