Skip to content Skip to sidebar Skip to footer

Reactjs And Autofocus

I have a react-bootstrap modal with an . I want to set the autofocus attribute on the The following works fine, but shows a warning in the console

Solution 1:

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

importReact, { useCallback } from'react'functionInputComponent() {
    const autoFocus = useCallback(el => el ? el.focus() : null, [])

    return<inputtype="text"ref={autoFocus} />
}

exportdefaultInputComponent

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

Solution 2:

Refs is what you want,

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

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

<input type="text"  ref={this.myRef} />

Solution 3:

If you are using react hooks, you could write your own simple auto focus hook:

import { useEffect, useState } from"react";

exportconstuseAutoFocus = (inputId: string) => {
    const [initialized, setInitialized] = useState(false);
    useEffect(() => {
        if(!initialized) {
            document.getElementById("email").focus();
            setInitialized(true);
        }
    });
};

and the simply use e.g.

useAutoFocus("email")

in your form.

Post a Comment for "Reactjs And Autofocus"