The focus call is something called a side effect. So you have to directly access the HTML dom element to call it.
Refs ( https://reactjs.org/docs/refs-and-the-dom.html )
Are the react way of accessing this native element. You basically setup a container variable and assign it to the react element interested. Behind the scenes react will link that variable to the native dom element on which you can call the primitive focus function.
There are two different ways to do this which is shown below.
import React, { useRef } from "react";
import "./styles.css";
function FormFunctionalComponent() {
const input1 = useRef(null);
const input2 = useRef(null);
const handleClick1 = () => {
input1.current.focus();
};
const handleClick2 = () => {
input2.current.focus();
};
return (
<div className="App">
<h1>Functional Component</h1>
<button onClick={handleClick1}>One</button>
<button onClick={handleClick2}>Two</button>
<div>
<input ref={input1} type="text" name="one" id="one" placeholder="one" />
</div>
<div>
<input ref={input2} type="text" name="two" id="two" placeholder="two" />
</div>
</div>
);
}
class FormClassComponent extends React.Component {
constructor(props) {
super(props);
this.input1 = React.createRef();
this.input2 = React.createRef();
}
handleClick1 = () => {
this.input1.current.focus();
};
handleClick2 = () => {
this.input2.current.focus();
};
render() {
return (
<div className="App">
<h1>Class Component</h1>
<button onClick={this.handleClick1}>One</button>
<button onClick={this.handleClick2}>Two</button>
<div>
<input ref={this.input1} type="text" name="one" id="one" placeholder="one" />
</div>
<div>
<input ref={this.input2} type="text" name="two" id="two" placeholder="two" />
</div>
</div>
);
}
}
export default function App() {
return (
<>
<FormFunctionalComponent /> <hr />
<FormClassComponent />
</>
);
}
This is the working codesandbox sample.
https://codesandbox.io/s/blissful-fog-xoj9t?file=/src/App.js