I'm trying to set the first input field in any form to be focused. So, what is the best practice to implement something like this? And how could I check the type of the field? is it text, number, checkbox or etc.?
Is it by listening to @redux-form
actions, and then dispatch a focus action?
Can any one suggest a solution ?
To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.
You can add an input field in a redux form using a Field tag that can be imported from redux-form import { Field, reduxForm } from 'redux-form'; <Field name="textField" component="input" type="text" //This can be password, email, number, etc placeholder="Text type field" />
By setting the focus on the first form field, we indicate the user from where to begin. It increases the readability of a form in a webpage. There are various approaches to do so, we’ll explain two of them with suitable examples. Approach 1: Using HTML <input> autofocus attribute.
Autofocus is a boolean attribute, used along with an <input> element in a form. The form field is focused on automatically when the page loads. Approach 2: Using focus () method in JavaScript. The focus () method can be used to set both automatic and manual focus to the specified form field. You can read more about this method here.
Focus the first input (field) element with an error (after submit) I used autoFocus= {true} on the first <input /> on the page so that when the component mounts, it will get focus. This took longer and was more convoluted. I'm keeping out code that isn't relevant to the solution for brevity.
I think that for redux-form (v6+) the current state of art is to provide autoFocus
property for the <input />
which you would like to be auto focused.
Example:
<Field component={renderFirstInput} type="text" />
const renderFirstInput = field => {
return ( <input {...field.input} autoFocus /> )
}
Here is the Github issue link
You may of course provide autoFocus
prop as a field.input
key.
Using this approach, you can configure your autoFocus
every time.
<Field component={renderFirstInput} autoFocus={true/false} />
const renderFirstInput = ({ autoFocus }) => {
return ( <input autoFocus={autoFocus} /> )
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With