Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus on first input field - redux-form

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 ?

like image 890
M1M6 Avatar asked Mar 25 '17 12:03

M1M6


People also ask

How do you know if input field is focused?

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.

How to add an input field in a redux form?

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

How to set the focus on the first form 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.

How to set autofocus on form fields in JavaScript?

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.

How to focus the first input element with an error (after submit)?

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.


2 Answers

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.

like image 71
jmarceli Avatar answered Oct 19 '22 19:10

jmarceli


Using this approach, you can configure your autoFocus every time.

<Field component={renderFirstInput} autoFocus={true/false} />

const renderFirstInput = ({ autoFocus }) => {
  return ( <input autoFocus={autoFocus} /> )

}
like image 34
Thai Ha Avatar answered Oct 19 '22 21:10

Thai Ha