Set focus on input after render

Set focus on input after render

What’s the react way of setting focus on a particular text field after the component is rendered?
Documentation seems to suggest using refs, e.g:
Set ref=”nameInput” on my input field in the render function, and then call:
this.refs.nameInput.getInputDOMNode().focus();

But where should I call this? I’ve tried a few places but I cannot get it to work.

Solutions/Answers:

Solution 1:

You should do it in componentDidMount and refs callback instead. Something like this

componentDidMount(){
   this.nameInput.focus(); 
}
class App extends React.Component{
  componentDidMount(){
    this.nameInput.focus();
  }
  render() {
    return(
      <div>
        <input 
          defaultValue="Won't focus" 
        />
        <input 
          ref={(input) => { this.nameInput = input; }} 
          defaultValue="will focus"
        />
      </div>
    );
  }
}
    
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>

Solution 2:

@Dhiraj’s answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=...

Note that in jsx it’s autoFocus (capital F) unlike plain old html which is case-insensitive.

Solution 3:

As of React 0.15, the most concise method is:

<input ref={input => input && input.focus()}/>

Solution 4:

If you just want to make autofocus in React, it’s simple.

<input autoFocus type="text" />

While if you just want to know where to put that code, answer is in componentDidMount().

v014.3

componentDidMount() {
    this.refs.linkInput.focus()
}

In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.

Read the API documents here: https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode

Solution 5:

Declarative Focus

Focus on mount

If you just want to focus an element when it mounts (initially renders) a simple use of the autoFocus attribute will do.

<input type="text" autoFocus />

Interactive focus with a useFocus hook

If you want to focus on an element according to some logic (a certain key was pressed, a certain button was clicked, or the expected number of chars were typed in an input) use a useFocus hook.

// General Focus Hook
const useFocus = (initialFocus = false, id = "") => {
    const [focus, setFocus] = useState(initialFocus)
    const setFocusWithTrueDefault = (param) => setFocus(isBoolean(param)? param : true)
    return ([
        setFocusWithTrueDefault, {
            autoFocus: focus,
            key: `${id}${focus}`,
            onFocus: () => setFocus(true),
            onBlur: () => setFocus(false),
        },
    ])
}


const FocusDemo = () => {

    const [value, setValue] = useState("")
    const [setFocus, focusProps] = useFocus(true)

    return (
        <> {/* React.Fragment */}
            <input
                onChange={(e)=>{
                    setValue(e.target.value)
                    if (e.target.value>=3){ setFocus(false) }
                }
                value={value}
                {...focusProps}
            />
            <button onClick={setFocus}>Refocus</button>
        </>
    )

}

For a more complete demo click here.

The disadvantages of using a Ref

An important advantage React provides as a framework is the ability to write declerative (rahter than imperative) code. The idea is you just declare what your UI looks like (for a given state or props). It makes code easier to understand and to debug, and requires less lines of code. When you use a ref you don’t follow this pattern.

The challenges of a declarative focus

Controlling focus declaratively presents some challenges, which could be solved gracefully with a useFocus hook.

  1. The only html tool that affects focus is the autoFocus attribute. This attribute can only set focus when the html element mounts (Just changing the value of the attribute won’t have any effect). The solution is to use the key attribute to re-mount the element every time we change the value of focus.
  2. Our React code is not the only source to control focus – the browser has it’s own mechanism to set focus. When a user clicks on another input in the page, the browser will focus on that input, and since only one element can have focus at a time, any other element will lose focus. We should reflect this in our state; We can achieve this by passing onFocus and onBlur to the input element and set the state accordingly.

Solution 6:

I just ran into this issue and I’m using react 15.0.1 15.0.2 and I’m using ES6 syntax and didn’t quite get what I needed from the other answers since v.15 dropped weeks ago and some of the this.refs properties were deprecated and removed.

In general, what I needed was:

  1. Focus the first input (field) element when the component mounts
  2. Focus the first input (field) element with an error (after submit)

I’m using:

  • React Container/Presentation Component
  • Redux
  • React-Router

Focus the First Input Element

I used autoFocus={true} on the first <input /> on the page so that when the component mounts, it will get focus.

Focus the First Input Element with an Error

This took longer and was more convoluted. I’m keeping out code that isn’t relevant to the solution for brevity.

Redux Store / State

I need a global state to know if I should set the focus and to disable it when it was set, so I don’t keep re-setting focus when the components re-render (I’ll be using componentDidUpdate() to check for setting focus.)

This could be designed as you see fit for you application.

{
    form: {
        resetFocus: false,
    }
}

Container Component

The component will need to have the resetfocus property set and a callBack to clear the property if it ends up setting focus on itself.

Also note, I organized my Action Creators into separate files mostly due to my project is fairly large and I wanted to break them up into more manageable chunks.

import { connect } from 'react-redux';
import MyField from '../presentation/MyField';
import ActionCreator from '../actions/action-creators';

function mapStateToProps(state) {
    return {
        resetFocus: state.form.resetFocus
    }
}

function mapDispatchToProps(dispatch) {
    return {
        clearResetFocus() {
            dispatch(ActionCreator.clearResetFocus());
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MyField);

Presentation Component

import React, { PropTypes } form 'react';

export default class MyField extends React.Component {
    // don't forget to .bind(this)
    constructor(props) {
        super(props);
        this._handleRef = this._handleRef.bind(this);
    }

    // This is not called on the initial render so
    // this._input will be set before this get called
    componentDidUpdate() {
        if(!this.props.resetFocus) {
            return false;
        }

        if(this.shouldfocus()) {
            this._input.focus();
            this.props.clearResetFocus();
        }
    }

    // When the component mounts, it will save a 
    // reference to itself as _input, which we'll
    // be able to call in subsequent componentDidUpdate()
    // calls if we need to set focus.
    _handleRef(c) {
        this._input = c;
    }

    // Whatever logic you need to determine if this
    // component should get focus
    shouldFocus() {
        // ...
    }

    // pass the _handleRef callback so we can access 
    // a reference of this element in other component methods
    render() {
        return (
            <input ref={this._handleRef} type="text" />
        );
    }
}

Myfield.propTypes = {
    clearResetFocus: PropTypes.func,
    resetFocus: PropTypes.bool
}

Overview

The general idea is that each form field that could have an error and be focused needs to check itself and if it needs to set focus on itself.

There’s business logic that needs to happen to determine if the given field is the right field to set focus to. This isn’t shown because it will depend on the individual application.

When a form is submitted, that event needs to set the global focus flag resetFocus to true. Then as each component updates itself, it will see that it should check to see if it gets the focus and if it does, dispatch the event to reset focus so other elements don’t have to keep checking.

edit
As a side note, I had my business logic in a “utilities” file and I just exported the method and called it within each shouldfocus() method.

Cheers!