Home > OS >  Focus input after modal appear React
Focus input after modal appear React

Time:09-06

I made a custom Modal. This modal appears after clicking on a button. The modal contains inputs. Input is also a component.

Input component,

<ModalInput label="Name" focus={true} />

ModalInput.jsx,

const ModalInput = ({ label, focus }) => {
  return (
    <div className="input-row">
      <div className="label">{label}</div>
      <input autoFocus={focus} type="text" style={{ width: "300px" }} />
    </div>
  );
};

ModalInput.defaultProps = {
  focus: false,
};

export default ModalInput;

I'm passing a prop called focus with the input component. The default value is false. But hereafter the modal appears it's not focusing on the input.

CodePudding user response:

I found this conversation telling that this is an expected behavior.

React autoFocus attribute is not rendered

You can use an useRef and set the focus when the component is ready:

    const inputEl = useRef(null);

    useEffect(() => {
        inputEl.current.focus();
    }, []);

    return <div>
        <input autofocus="true" ref={inputEl} />
    </div>;
}
  • Related