Listing 18-7: Using a ref to set keyboard focus
import {useState,useRef,useEffect} from 'react';
import Modal from './Modal';
import './styles.css';
function App() {
const CSCRef = useRef()
const[isModalOpen,setModalOpen] = useState(false);
const toggleModal = () => {
setModalOpen(()=>!isModalOpen);
}
useEffect(() => {
setTimeout(()=>{!isModalOpen && CSCRef.current.focus()},1000)
}, [isModalOpen]);
return (
<div style={{padding:"60px"}}>
<label>Card Security Code:<input ref={CSCRef} /></label>
<button onClick={toggleModal}>What's This?</button>
<Modal title="What is the CSC Code?" isOpen={isModalOpen}>
<p>A credit card security code is the 3-4 digit number that
is printed, not embossed, on all credit cards. The length
and location of a credit card’s security code depend on
what network the card is on. </p>
<button onClick={toggleModal}>close modal</button>
</Modal>
</div>
);
}
export default App;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.