Skip to content

Instantly share code, notes, and snippets.

@starkraving
Last active June 22, 2021 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starkraving/2a72bc48008485b8f25f397c3c461c49 to your computer and use it in GitHub Desktop.
Save starkraving/2a72bc48008485b8f25f397c3c461c49 to your computer and use it in GitHub Desktop.
Using button for input focus
import { useRef } from "react";
const Component1 = ({ inputRef }) => {
const handleClick = () => {
inputRef.current.focus();
};
return (
<div className='col-sm-2 col-xs-12 p-2 border border-primary'>
<button className='btn btn-primary' onClick={handleClick}>
Click to focus
</button>
</div>
);
};
const Component2 = ({ inputRef }) => {
return (
<div className='col-sm-10 col-xs-12 p-2 border border-primary'>
<input ref={inputRef} type='text' className='form-control' />
</div>
);
};
export default function App() {
const inputRef = useRef();
return (
<div className='container'>
<h1 className='text-center'>Button for Focus</h1>
<div className='row'>
<Component1 inputRef={inputRef} />
<Component2 inputRef={inputRef} />
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment