React - Create multiple useRefs in one line using object or array - reactjs

I want to declare multiple useRefs and have them all in 1 object or an array. If that's not possible, then any means of declaring multiple refs in one line, like array destructuring
I tried these so far, neither worked.
attempt 1
const inputRefs = useRef({ input1: null, input2: null, input3: null, input4: null })
function focusInput() {
inputRefs.input2.current.focus()
}
return (
<div>
<input type="text" ref={inputRefs.input1} />
<input type="text" ref={inputRefs.input2} />
<input type="text" ref={inputRefs.input3} />
<input type="text" ref={inputRefs.input4} />
<button onClick={focusInput}>focus</button>
</div>
)
attempt 2
const [input1, input2, input3, input4] = Array(4).fill(useRef(null))
function focusInput() {
input2.current.focus()
}
return (
<div>
<input type="text" ref={input1} />
<input type="text" ref={input2} />
<input type="text" ref={input3} />
<input type="text" ref={input4} />
<button onClick={focusInput}>focus</button>
</div>
)
note I only have 4 inputs in the example, but in reality I have much more so hence I want to find a way. Thanks

You can set ref on your inputs wrapper and work with inputs through DOM API.
const containerRef = useRef(null);
function focusInput() {
const containerNode = containerRef.current;
containerNode.childNodes[2].focus();
}
return (
<div ref={containerRef}>
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<button onClick={focusInput}>focus</button>
</div>
)

Few things to correct.
The useRef is a react hook (which should be defined in the top level of the function). Therefore, to create refs and store them in an array, you should use createRef.
Array.fill does not create 4 new refs instead of that share a single ref. That's why even though you clicked on the button always last input is always referred to. To get rid of that, use Array.from like below.
import { createRef } from "react";
export default function App() {
const [input1, input2, input3, input4] = Array.from({ length: 4 }, () =>
createRef(null)
);
function focusInput() {
input2.current.focus();
}
return (
<div>
<input type="text" ref={input1} />
<input type="text" ref={input2} />
<input type="text" ref={input3} />
<input type="text" ref={input4} />
<button onClick={focusInput}>focus</button>
</div>
);
}

kk I found a similar way to my first one but it works. Further suggestions are also welcome
import { useRef } from "react";
export default function App() {
const inputRefs = {input1: useRef(null), input2: useRef(null), input3: useRef(null), input4: useRef(null)}
function focusInput() {
inputRefs.input2.current.focus();
}
return (
<div>
<input type="text" ref={inputRefs.input1} />
<input type="text" ref={inputRefs.input2} />
<input type="text" ref={inputRefs.input3} />
<input type="text" ref={inputRefs.input4} />
<button onClick={focusInput}>focus</button>
</div>
);
}

You can simply use react-use-refs it used a clever generator to create how many useRef you need.
import useRefs from "react-use-refs";
function Demo() {
const [someRef, anotherRef] = useRefs();
return (
<div>
<div ref={someRef}>someRef</div>
<div ref={anotherRef}>anotherRef</div>
</div>
)
}
Or you can implement one yourself
import {useRef} from "react";
const MAX_ITERATIONS_COUNT = 50;
function iterator() {
return this;
}
export default function useRefs(...args) {
let count = 0;
return {
next() {
if (++count > MAX_ITERATIONS_COUNT) {
throw new Error(
"useMultipleRefs: reached more than 50 refs. This hook can be used exclusively with the array destructuring syntax."
);
}
return {
done: false,
value: useRef(args[count - 1] ?? args.at(-1)),
};
},
[Symbol.iterator]: iterator,
};
}
Or using my version from that collection here npm i #perymimon/react-hooks
import {useRefs} from #perymimon/react-hooks
// or
import useRefs from #perymimon/react-hooks/src/useRefs

Related

remove the value enterd in input fild after submistion :react js [duplicate]

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.
<form id="create-course-form">
<input type="text" name="course_Name" ref="fieldName">
<input type="text" name="course_org" ref="fieldOrg">
<input type="text" name="course_Number" ref="fieldNum">
<input type="submit" name="saveCourse" value="Create">
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}>
</form>
What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.
cancelCourse(){
this.refs.fieldName.value="";
this.refs.fieldorg.value="";
this.refs.fieldNum.value="";
}
However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');
The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks #Dan-Esparza for providing the links.
Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.
Clearing a form with uncontrolled fields
You can clear the entire form rather than each form field individually.
cancelCourse = () => {
document.getElementById("create-course-form").reset();
}
render() {
return (
<form id="create-course-form">
<input />
<input />
...
<input />
</form>
);
}
If your form didn't have an id attribute you could use a ref as well:
cancelCourse = () => {
this.myFormRef.reset();
}
render() {
return (
<form ref={(el) => this.myFormRef = el;}>
<input />
<input />
...
<input />
</form>
);
}
Clearing a form with controlled fields
If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.
If they are declared individually, you need to reset each one explicitly:
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
...
inputVal_n: "",
});
}
render() {
return (
<input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
<input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
...
<input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
};
}
handleInput1Change = (e) => {
this.setState({inputVal_1: e.target.value});
}
handleInput2Change = (e) => {
this.setState({inputVal_2: e.target.value});
}
handleInput3Change = (e) => {
this.setState({inputVal_3: e.target.value});
}
handleInput4Change = (e) => {
this.setState({inputVal_4: e.target.value});
}
handleInput5Change = (e) => {
this.setState({inputVal_5: e.target.value});
}
handleInput6Change = (e) => {
this.setState({inputVal_6: e.target.value});
}
handleInput7Change = (e) => {
this.setState({inputVal_7: e.target.value});
}
handleInput8Change = (e) => {
this.setState({inputVal_8: e.target.value});
}
handleInput9Change = (e) => {
this.setState({inputVal_9: e.target.value});
}
handleInput10Change = (e) => {
this.setState({inputVal_10: e.target.value});
}
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
});
}
render() {
return (
<form>
<input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
<input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
<input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
<input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
<input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
<input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
<input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
<input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
<input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
<input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.
In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.
To reset the form, we only need to set our input object back to being empty again.
The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return (
<form>
{[...Array(n)].map(
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />
)}
</form>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal: {}
};
}
handleInputChange = (idx, {target}) => {
this.setState(({inputVal}) => {
inputVal[idx] = target.value;
return inputVal;
});
}
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return(
<form>
{[...Array(10)].map( //create an array with a length of 10
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} /> //bind the index to the input handler
)}
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Very easy:
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
// If using class component
<form onSubmit={this.handleSubmit.bind(this)}>
...
</form>
// If using function component
<form onSubmit={handleSubmit}>
...
</form>
Using event.target.reset() only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
Here's an update to Chris's answer above, using modern React hooks.
Same high level idea; your form can be either a Controlled or Uncontrolled component.
Uncontrolled components:
Uncontrolled components leave state management up to the browser. That means you have to ask the browser to reset the form inputs. To do that, capture the form element as a ref, and then call the submit() method on that element.
export default function Form() {
const ref = React.useRef();
function reset(ev) {
ev.preventDefault();
ref.current.reset();
}
return (
<form ref={ref}>
<label htmlFor="email">Email Address</label>
<input id="email" type="email" name="email" />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" />
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Controlled components:
With a controlled component, you manage the state in React. That means you have to create the initial state, and update it every time an input changes. In this world, resetting the form is just a matter of setting the form state back to its initial state.
export default function Form() {
const [state, setState] = React.useState({ email: "", message: "" });
function reset(ev) {
ev.preventDefault();
setState({ email: "", message: "" });
}
return (
<form className="Form">
<label htmlFor="email">Email Address</label>
<input
id="email"
type="email"
name="email"
value={state.email}
onChange={(ev) => {
setState({ ...state, email: ev.target.value });
}}
/>
<label htmlFor="message">Message</label>
<textarea
id="message"
name="message"
value={state.message}
onChange={(ev) => {
setState({ ...state, message: ev.target.value });
}}
/>
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Full example at https://codesandbox.io/s/reactformreset-10cjn3
Following code should reset the form in one click.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(e){
this.refs.form.reset();
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit} ref="form">
<input type="text" placeholder="First Name!" ref='firstName'/><br/<br/>
<input type="text" placeholder="Last Name!" ref='lastName'/><br/><br/>
<button type="submit" >submit</button>
</form>
</div>
}
}
To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :
// clear all your form
Object.keys(this.state).map((key, index) => {
this.setState({[key] : ""});
});
If your form is among other fields, you can simply insert them in a particular field of the state like that:
state={
form: {
name:"",
email:""}
}
// handle set in nested objects
handleChange = (e) =>{
e.preventDefault();
const newState = Object.assign({}, this.state);
newState.form[e.target.name] = e.target.value;
this.setState(newState);
}
// submit and clear state in nested object
onSubmit = (e) =>{
e.preventDefault();
var form = Object.assign({}, this.state.form);
Object.keys(form).map((key, index) => {
form[key] = "" ;
});
this.setState({form})
}
This one works best to reset the form.
import React, { Component } from 'react'
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state ///>>>>>>>>> note this one.
}
resetForm = () => {
this.setState(this.baseState) ///>>>>>>>>> note this one.
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val })
render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}
When the form is submitted, the 'event' will be passed as an argument to the handleSubmit method, and if that you can access the <form> element by typing event.target. then you just need to reset the form using .reset() form method.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
handleSubmit = (event)=>{
event.preventDefault()
....
event.target.reset()
}
render() {
return (
<>
<form onSubmit={this.handleSubmit}>
<label htmlFor='movieTitle'>Title</label>
<input name='movieTitle' id='movieTitle' type='text' />
<input type='submit' value='Find Movie Info' />
</form>
</>
)
}
I don't know if this is still relevant. But when I had similar issue this is how I resolved it.
Where you need to clear an uncontrolled form you simply do this after submission.
this.<ref-name-goes-here>.setState({value: ''});
Hope this helps.
import React, { Component } from 'react'
export default class Form extends Component {
constructor(props) {
super(props)
this.formRef = React.createRef()
this.state = {
email: '',
loading: false,
eror: null
}
}
reset = () => {
this.formRef.current.reset()
}
render() {
return (
<div>
<form>
<input type="email" name="" id=""/>
<button type="submit">Submit</button>
<button onClick={()=>this.reset()}>Reset</button>
</form>
</div>
)
}
}
/*
See newState and use of it in eventSubmit() for resetting all the state.
I have tested it is working for me. Please let me know for mistakes
*/
import React from 'react';
const newState = {
fullname: '',
email: ''
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
fullname: ' ',
email: ' '
}
this.eventChange = this
.eventChange
.bind(this);
this.eventSubmit = this
.eventSubmit
.bind(this);
}
eventChange(event) {
const target = event.target;
const value = target.type === 'checkbox'
? target.type
: target.value;
const name = target.name;
this.setState({[name]: value})
}
eventSubmit(event) {
alert(JSON.stringify(this.state))
event.preventDefault();
this.setState({...newState});
}
render() {
return (
<div className="container">
<form className="row mt-5" onSubmit={this.eventSubmit}>
<label className="col-md-12">
Full Name
<input
type="text"
name="fullname"
id="fullname"
value={this.state.fullname}
onChange={this.eventChange}/>
</label>
<label className="col-md-12">
email
<input
type="text"
name="email"
id="email"
value={this.state.value}
onChange={this.eventChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
)
}
}
export default Form;
the easiest way is doing it regularly with just HTML and using the button type "reset" there is no need to mess with anything in react at all, no state, no nothing.
import React, {useState} from 'react'
function HowReactWorks() {
return (
<div>
<form>
<div>
<label for="name">Name</label>
<input type="text" id="name" placeholder="name" />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" placeholder="password" />
</div>
<button type="reset">Reset</button>
<button>Submit</button>
</form>
</div>
)
}
export default HowReactWorks
edited for the people that don't know how to include HTML in react
You can use this method as well
const resetData = (e) => {
e.preventDefault();
settitle("");
setdate("");
};
<input type="text" onChange={(e) => settitle(e.target.value)} value={title} />
<input type="date" onChange={(e) => setdate(e.target.value)} value={date} />
<button onClick={resetData}>Reset Data</button>
This is the solution that worked for me, in the case of parent component triggering reset of child controlled input components:
const ParentComponent = () => {
const [reset, setReset] = useState()
const submitHandler = (e) => {
e.preventDefault()
//do your stuff
setReset(Date.now()) // pass some value to trigger update
}
return (
<form onSubmit={submitHandler}>
<ChildInputComponent reset={reset} />
<ChildInputComponent reset={reset} />
</form>
)
}
const ChildInputComponent = ({reset}) => {
const [value, setValue] = useState()
useEffect(() => {
setValue('')
}, [reset])
return <input value={value} onChange={(e) => setValue(e.target.value)} />
}
Assuming you declared
const [inputs, setInputs] = useState([]);
As multiple parameters. You can actually reset the items using this syntax:
setInputs([]);
Just in case, this how you define handleChange.
You can use this form or any ways you want.
const handleChange = (event) => {
const name = event.target.name;
const email = event.target.email;
const message = event.target.message;
const value = event.target.value;
setInputs(values => ({...values, [name]: value, [email]: value, [message]: value}))
}
You can use this form as an example.
<form onSubmit={handleSubmit}>
<div className="fields">
<div className="field half">
<label for="name">Name</label>
<input value={inputs.name || ''} type="text" name="name" id="nameId" onChange={handleChange} maxLength="30" />
</div>
<div className="field half">
<label for="email">Email</label>
<input value={inputs.email || ''} type="text" name="email" id="emailId" onChange={handleChange} maxLength="40"/>
</div>
<div className="field">
<label for="message">Message</label>
<textarea value={inputs.message || ''} name="message" id="messageId" rows="6" onChange={handleChange} maxLength="400" />
</div>
</div>
<ul className="actions">
<li><input type="submit" value="Send Message" className="primary" /></li>
<li><input onClick={resetDetails} type="reset" value="Clear" /></li>
</ul>
</form>
This is just one of many ways to declare forms. Good luck!
const onReset = () => {
form.resetFields();
};
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
Why not use HTML-controlled items such as <input type="reset">

How can I get radio button value and upload it into firebase?

In this code, I want to upload the radio button value and store it in firebase database.I want use the simplest way to solve that. I see other code will use constructor but I do not know whether I can use simpler way to solve it. how can I do that ?
import React, { useState } from "react";
import ReactPlayer from "react-player";
import Array from "../Array";
import firebase from "firebase";
export default () => {
const [selected, setSelected] = useState("");
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer"
value="real"
onChange={e => setSelected(e.target.value)}
/>
real
</label>
<label>
<input
type="radio"
name="answer"
value="fake"
onChange={e => setSelected(e.target.value)}
/>
fake
</label>
</div>
);
};
I would do it like this:
import React from "react";
....
export default () => {
const [state, setState] = React.useState({});
const handleInputChange = e => {
const { name, value } = e.target;
console.log(name, value);
setState(state => {
const newState = { ...state, [name]: value }
//post newState to firebase
return newState
});
};
return (
<div>
<div className="video">
<ReactPlayer url={Array[0]} playing />
</div>
<div>{JSON.stringify(state)}</div>
<label>Guess whether this video is fake or real ?</label> <br />
<label>
<input
type="radio"
name="answer1"
value="real"
onChange={handleInputChange}
/>
real
</label>
<label>
<input
type="radio"
name="answer2"
value="fake"
onChange={handleInputChange}
/>
fake
</label>
</div>
);
};

AutoFocus doesn't work in React

I have a problem with autoFocus. It doesn't work for me, but using it:
<input onChange={this.handleName} value={this.state.name} placeholder="Name..." type="text" autoFocus />
None of these worked for me:
<input type="text" autoFocus .../>
<input type="text" autoFocus={true} .../>
<input type="text" autoFocus="true" .../>
<input type="text" autoFocus="autofocus" .../>
…even though in each case, the web inspector showed that <input type="text" autofocus .../> was rendered 🤔
Perhaps it's because of this phenomenon, I'm not sure:
If you render your React component into a detached element, React will call focus() too soon. This will result in the input not focusing when your React tree gets added to the DOM.
This did work for me:
import React, { useRef, useEffect } from "react";
export default function SignIn() {
const inputElement = useRef(null);
useEffect(() => {
if (inputElement.current) {
inputElement.current.focus();
}
}, []);
return (
<div>
<form action="...">
<input
ref={inputElement} // yes, this is working in Chrome on Mac
type="text" // allows username also; type 'email' woud insist on '#' sign
name="email"
placeholder="Email address"
autoComplete="email"
required
...
/>
</form>
</div>
);
}
That's strategy #2 from Daniel Johnson
Likely something else you are doing that is causing it to fail. It works fine in this simple example:
const App = React.createClass({
render() {
return (
<input
placeholder = "Name..."
type = "text"
autoFocus
/ >
);
}
});
ReactDOM.render( <
App / > ,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
For React function components when you get the error
Warning: Function components cannot be given refs. Attempts to access
this ref will fail. Did you mean to use React.forwardRef()?
import React, { useEffect, useRef } from 'react';
const InputField = () => {
const inputElement = useRef(null);
useEffect(() => {
inputElement.current?.focus();
}, []);
return (
<form action="...">
<input type="text" innerRef={inputElement} />
</form>
);
};
export default InputField;
If you use typescript and the compiler complains
Property 'focus' does not exist on type 'never'.ts(2339)
initialize inputElement with
const inputElement = useRef<HTMLInputElement>(null);
I had two Input's which I applied autoFocus to, one worked and the other didn't. They were both reactstrap Input fields:
import { Button, Input } from 'reactstrap';
I discovered that one had a type and no name, which was the one that worked. So I changed the other to be the same and it started working:
<Input
autoFocus="autofocus"
id="code"
type="text"
value={props.codeValue}
onChange={props.onCodeChange}
onKeyPress={event => {
if (event.key === 'Enter') {
confirmCode();
}
}}
/>
place that "autoFocus" infront of "input"
<input autoFocus type='text' ...others />
idk but this worked for me !
This is what worked for me on the functional react component as the autoFocus attribute did not work out of the box:
import React, { useCallback } from 'react';
const FeebackForm = () => {
const autoFocusFn = useCallback(element => (element ? element.focus() : null), []);
return (
<form action="...">
<input type="text" name="customerName" ref={autoFocusFn} />
</form>
);
};
export default FeebackForm;
If you're working on a conditional input component that appears post page is loaded on some user interaction, use react cleanup design to focus the input element.
jsx:
{ this.state.showInput && <input ref={ref => {this.inputRef = ref}} /> }
Class components:
this.setState({showInput: true},
() => {
this.inputRef && this.inputRef.focus()
}
)
Functional components:
useEffect(() => {
return () => {
this.inputRef && this.inputRef.focus()
}
}, [showInput])
If auto focus doesn't work for you then you can try using the .focus() function of javascript, which will always work :)
componentDidMount() {
document.getElementById("name").focus();
}
<input id="name" onChange={this.handleName} value={this.state.name} placeholder="Name..." type="text" autoFocus />

Clear and reset form input fields

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.
<form id="create-course-form">
<input type="text" name="course_Name" ref="fieldName">
<input type="text" name="course_org" ref="fieldOrg">
<input type="text" name="course_Number" ref="fieldNum">
<input type="submit" name="saveCourse" value="Create">
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}>
</form>
What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.
cancelCourse(){
this.refs.fieldName.value="";
this.refs.fieldorg.value="";
this.refs.fieldNum.value="";
}
However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');
The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks #Dan-Esparza for providing the links.
Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.
Clearing a form with uncontrolled fields
You can clear the entire form rather than each form field individually.
cancelCourse = () => {
document.getElementById("create-course-form").reset();
}
render() {
return (
<form id="create-course-form">
<input />
<input />
...
<input />
</form>
);
}
If your form didn't have an id attribute you could use a ref as well:
cancelCourse = () => {
this.myFormRef.reset();
}
render() {
return (
<form ref={(el) => this.myFormRef = el;}>
<input />
<input />
...
<input />
</form>
);
}
Clearing a form with controlled fields
If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.
If they are declared individually, you need to reset each one explicitly:
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
...
inputVal_n: "",
});
}
render() {
return (
<input value={this.state.inputVal_1} onChange={this.handleInput1Change}>
<input value={this.state.inputVal_2} onChange={this.handleInput2Change}>
...
<input value={this.state.inputVal_n} onChange={this.handleInputnChange}>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
};
}
handleInput1Change = (e) => {
this.setState({inputVal_1: e.target.value});
}
handleInput2Change = (e) => {
this.setState({inputVal_2: e.target.value});
}
handleInput3Change = (e) => {
this.setState({inputVal_3: e.target.value});
}
handleInput4Change = (e) => {
this.setState({inputVal_4: e.target.value});
}
handleInput5Change = (e) => {
this.setState({inputVal_5: e.target.value});
}
handleInput6Change = (e) => {
this.setState({inputVal_6: e.target.value});
}
handleInput7Change = (e) => {
this.setState({inputVal_7: e.target.value});
}
handleInput8Change = (e) => {
this.setState({inputVal_8: e.target.value});
}
handleInput9Change = (e) => {
this.setState({inputVal_9: e.target.value});
}
handleInput10Change = (e) => {
this.setState({inputVal_10: e.target.value});
}
cancelCourse = () => {
this.setState({
inputVal_1: "",
inputVal_2: "",
inputVal_3: "",
inputVal_4: "",
inputVal_5: "",
inputVal_6: "",
inputVal_7: "",
inputVal_8: "",
inputVal_9: "",
inputVal_10: ""
});
}
render() {
return (
<form>
<input value={this.state.inputVal_1} onChange={this.handleInput1Change} />
<input value={this.state.inputVal_2} onChange={this.handleInput2Change} />
<input value={this.state.inputVal_3} onChange={this.handleInput3Change} />
<input value={this.state.inputVal_4} onChange={this.handleInput4Change} />
<input value={this.state.inputVal_5} onChange={this.handleInput5Change} />
<input value={this.state.inputVal_6} onChange={this.handleInput6Change} />
<input value={this.state.inputVal_7} onChange={this.handleInput7Change} />
<input value={this.state.inputVal_8} onChange={this.handleInput8Change} />
<input value={this.state.inputVal_9} onChange={this.handleInput9Change} />
<input value={this.state.inputVal_10} onChange={this.handleInput10Change} />
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.
In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.
To reset the form, we only need to set our input object back to being empty again.
The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return (
<form>
{[...Array(n)].map(
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />
)}
</form>
);
}
Demo below:
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputVal: {}
};
}
handleInputChange = (idx, {target}) => {
this.setState(({inputVal}) => {
inputVal[idx] = target.value;
return inputVal;
});
}
cancelCourse = () => {
this.setState({inputVal: {}});
}
render() {
return(
<form>
{[...Array(10)].map( //create an array with a length of 10
(item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} /> //bind the index to the input handler
)}
<input type="submit" name="saveCourse" value="Create" />
<input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Very easy:
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
// If using class component
<form onSubmit={this.handleSubmit.bind(this)}>
...
</form>
// If using function component
<form onSubmit={handleSubmit}>
...
</form>
Using event.target.reset() only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:
import React, { Component } from 'react'
class MyForm extends Component {
initialState = { name: '' }
state = this.initialState
handleFormReset = () => {
this.setState(() => this.initialState)
}
render() {
return (
<form onReset={this.handleFormReset}>
<div>
<label htmlFor="name">Name</label>
<input
type="text"
placeholder="Enter name"
name="name"
value={name}
onChange={this.handleInputOnChange}
/>
</div>
<div>
<input
type="submit"
value="Submit"
/>
<input
type="reset"
value="Reset"
/>
</div>
</form>
)
}
}
ContactAdd.propTypes = {}
export default MyForm
You can also do it by targeting the current input, with anything.target.reset() . This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
Here's an update to Chris's answer above, using modern React hooks.
Same high level idea; your form can be either a Controlled or Uncontrolled component.
Uncontrolled components:
Uncontrolled components leave state management up to the browser. That means you have to ask the browser to reset the form inputs. To do that, capture the form element as a ref, and then call the submit() method on that element.
export default function Form() {
const ref = React.useRef();
function reset(ev) {
ev.preventDefault();
ref.current.reset();
}
return (
<form ref={ref}>
<label htmlFor="email">Email Address</label>
<input id="email" type="email" name="email" />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" />
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Controlled components:
With a controlled component, you manage the state in React. That means you have to create the initial state, and update it every time an input changes. In this world, resetting the form is just a matter of setting the form state back to its initial state.
export default function Form() {
const [state, setState] = React.useState({ email: "", message: "" });
function reset(ev) {
ev.preventDefault();
setState({ email: "", message: "" });
}
return (
<form className="Form">
<label htmlFor="email">Email Address</label>
<input
id="email"
type="email"
name="email"
value={state.email}
onChange={(ev) => {
setState({ ...state, email: ev.target.value });
}}
/>
<label htmlFor="message">Message</label>
<textarea
id="message"
name="message"
value={state.message}
onChange={(ev) => {
setState({ ...state, message: ev.target.value });
}}
/>
<button type="submit">Submit</button>
<button onClick={reset}>Reset</button>
</form>
);
}
Full example at https://codesandbox.io/s/reactformreset-10cjn3
Following code should reset the form in one click.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.handleSubmit=this.handleSubmit.bind(this);
}
handleSubmit(e){
this.refs.form.reset();
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit} ref="form">
<input type="text" placeholder="First Name!" ref='firstName'/><br/<br/>
<input type="text" placeholder="Last Name!" ref='lastName'/><br/><br/>
<button type="submit" >submit</button>
</form>
</div>
}
}
To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :
// clear all your form
Object.keys(this.state).map((key, index) => {
this.setState({[key] : ""});
});
If your form is among other fields, you can simply insert them in a particular field of the state like that:
state={
form: {
name:"",
email:""}
}
// handle set in nested objects
handleChange = (e) =>{
e.preventDefault();
const newState = Object.assign({}, this.state);
newState.form[e.target.name] = e.target.value;
this.setState(newState);
}
// submit and clear state in nested object
onSubmit = (e) =>{
e.preventDefault();
var form = Object.assign({}, this.state.form);
Object.keys(form).map((key, index) => {
form[key] = "" ;
});
this.setState({form})
}
This one works best to reset the form.
import React, { Component } from 'react'
class MyComponent extends Component {
constructor(props){
super(props)
this.state = {
inputVal: props.inputValue
}
// preserve the initial state in a new object
this.baseState = this.state ///>>>>>>>>> note this one.
}
resetForm = () => {
this.setState(this.baseState) ///>>>>>>>>> note this one.
}
submitForm = () => {
// submit the form logic
}
updateInput = val => this.setState({ inputVal: val })
render() {
return (
<form>
<input
onChange={this.updateInput}
type="text
value={this.state.inputVal} />
<button
onClick={this.resetForm}
type="button">Cancel</button>
<button
onClick={this.submitForm}
type="submit">Submit</button>
</form>
)
}
}
When the form is submitted, the 'event' will be passed as an argument to the handleSubmit method, and if that you can access the <form> element by typing event.target. then you just need to reset the form using .reset() form method.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
handleSubmit = (event)=>{
event.preventDefault()
....
event.target.reset()
}
render() {
return (
<>
<form onSubmit={this.handleSubmit}>
<label htmlFor='movieTitle'>Title</label>
<input name='movieTitle' id='movieTitle' type='text' />
<input type='submit' value='Find Movie Info' />
</form>
</>
)
}
I don't know if this is still relevant. But when I had similar issue this is how I resolved it.
Where you need to clear an uncontrolled form you simply do this after submission.
this.<ref-name-goes-here>.setState({value: ''});
Hope this helps.
import React, { Component } from 'react'
export default class Form extends Component {
constructor(props) {
super(props)
this.formRef = React.createRef()
this.state = {
email: '',
loading: false,
eror: null
}
}
reset = () => {
this.formRef.current.reset()
}
render() {
return (
<div>
<form>
<input type="email" name="" id=""/>
<button type="submit">Submit</button>
<button onClick={()=>this.reset()}>Reset</button>
</form>
</div>
)
}
}
/*
See newState and use of it in eventSubmit() for resetting all the state.
I have tested it is working for me. Please let me know for mistakes
*/
import React from 'react';
const newState = {
fullname: '',
email: ''
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
fullname: ' ',
email: ' '
}
this.eventChange = this
.eventChange
.bind(this);
this.eventSubmit = this
.eventSubmit
.bind(this);
}
eventChange(event) {
const target = event.target;
const value = target.type === 'checkbox'
? target.type
: target.value;
const name = target.name;
this.setState({[name]: value})
}
eventSubmit(event) {
alert(JSON.stringify(this.state))
event.preventDefault();
this.setState({...newState});
}
render() {
return (
<div className="container">
<form className="row mt-5" onSubmit={this.eventSubmit}>
<label className="col-md-12">
Full Name
<input
type="text"
name="fullname"
id="fullname"
value={this.state.fullname}
onChange={this.eventChange}/>
</label>
<label className="col-md-12">
email
<input
type="text"
name="email"
id="email"
value={this.state.value}
onChange={this.eventChange}/>
</label>
<input type="submit" value="Submit"/>
</form>
</div>
)
}
}
export default Form;
the easiest way is doing it regularly with just HTML and using the button type "reset" there is no need to mess with anything in react at all, no state, no nothing.
import React, {useState} from 'react'
function HowReactWorks() {
return (
<div>
<form>
<div>
<label for="name">Name</label>
<input type="text" id="name" placeholder="name" />
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" placeholder="password" />
</div>
<button type="reset">Reset</button>
<button>Submit</button>
</form>
</div>
)
}
export default HowReactWorks
edited for the people that don't know how to include HTML in react
You can use this method as well
const resetData = (e) => {
e.preventDefault();
settitle("");
setdate("");
};
<input type="text" onChange={(e) => settitle(e.target.value)} value={title} />
<input type="date" onChange={(e) => setdate(e.target.value)} value={date} />
<button onClick={resetData}>Reset Data</button>
This is the solution that worked for me, in the case of parent component triggering reset of child controlled input components:
const ParentComponent = () => {
const [reset, setReset] = useState()
const submitHandler = (e) => {
e.preventDefault()
//do your stuff
setReset(Date.now()) // pass some value to trigger update
}
return (
<form onSubmit={submitHandler}>
<ChildInputComponent reset={reset} />
<ChildInputComponent reset={reset} />
</form>
)
}
const ChildInputComponent = ({reset}) => {
const [value, setValue] = useState()
useEffect(() => {
setValue('')
}, [reset])
return <input value={value} onChange={(e) => setValue(e.target.value)} />
}
Assuming you declared
const [inputs, setInputs] = useState([]);
As multiple parameters. You can actually reset the items using this syntax:
setInputs([]);
Just in case, this how you define handleChange.
You can use this form or any ways you want.
const handleChange = (event) => {
const name = event.target.name;
const email = event.target.email;
const message = event.target.message;
const value = event.target.value;
setInputs(values => ({...values, [name]: value, [email]: value, [message]: value}))
}
You can use this form as an example.
<form onSubmit={handleSubmit}>
<div className="fields">
<div className="field half">
<label for="name">Name</label>
<input value={inputs.name || ''} type="text" name="name" id="nameId" onChange={handleChange} maxLength="30" />
</div>
<div className="field half">
<label for="email">Email</label>
<input value={inputs.email || ''} type="text" name="email" id="emailId" onChange={handleChange} maxLength="40"/>
</div>
<div className="field">
<label for="message">Message</label>
<textarea value={inputs.message || ''} name="message" id="messageId" rows="6" onChange={handleChange} maxLength="400" />
</div>
</div>
<ul className="actions">
<li><input type="submit" value="Send Message" className="primary" /></li>
<li><input onClick={resetDetails} type="reset" value="Clear" /></li>
</ul>
</form>
This is just one of many ways to declare forms. Good luck!
const onReset = () => {
form.resetFields();
};
state={
name:"",
email:""
}
handalSubmit = () => {
after api call
let resetFrom = {}
fetch('url')
.then(function(response) {
if(response.success){
resetFrom{
name:"",
email:""
}
}
})
this.setState({...resetFrom})
}
Why not use HTML-controlled items such as <input type="reset">

Why can't I type in my fields?

I am using redux-form and I cannot type inside of my inputs after I add the initialize method and componentDidUpdate(). When I try to type in my email no characters appear. I am guessing all the inputs become controlled? If so how would I handle that?
import { reduxForm, Field, initialize } from 'redux-form';
const CustomComponent = function(field) {
return(
<div>
<input { ...field.input } type={field.type} placeholder={field.placeholder} />
</div>
);
}
//class instantiation
componentDidUpdate(){
this.handleInitialize();
}
handleInitialize() {
const initData = {
"name": this.props.name
};
this.props.initialize(initData);
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form onSubmit={handleSubmit(this.onSubmit)}>
<div>
<Field name="name" component={CustomComponent} type="text" placeholder="Name" />
<Field name="email" component={CustomComponent} type="email" placeholder="Email" />
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
You can't define your CustomComponent inside the render() method. That will cause your component to lose focus when you first start typing into an input.
Have you set up the reducer properly in your Redux config?

Resources