Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS and autofocus

I have a react-bootstrap modal with an <input>. I want to set the autofocus attribute on the <input>

The following works fine, but shows a warning in the console

<input type="text" autofocus='true' />
Warning: Invalid DOM property `autofocus`. Did you mean `autoFocus`?

The following options do not work, in the sense that they do not focus the input when opening the modal:

<input type="text" autoFocus='true' />
<input type="text" autoFocus={true} />
<input type="text" autoFocus />

What is the recommended way of setting autofocus. Or how should I mute the warnings for the example that works well?

Note: This is react 16.8.6

like image 963
Andrei Cioara Avatar asked Dec 10 '22 02:12

Andrei Cioara


2 Answers

If you're using React Hooks, add useCallback() to your component and add a ref={callback} to the form control:

import React, { useCallback } from 'react'

function InputComponent() {
    const autoFocus = useCallback(el => el ? el.focus() : null, [])

    return <input type="text" ref={autoFocus} />
}

export default InputComponent

You can replace the <input> with a React Bootstrap FormControl too.

like image 119
Brent Washburne Avatar answered Dec 30 '22 15:12

Brent Washburne


Refs is what you want,

constructor(props) {
    super(props);
    this.myRef = React.createRef();
}

componentDidMount(){
  this.myRef.current.focus();
}

<input type="text"  ref={this.myRef} />
like image 21
ravibagul91 Avatar answered Dec 30 '22 15:12

ravibagul91