Focus Input On Mount
ReactJS
Medium
5 views
Problem Description
Focus an input when the component mounts.
Output Format
Render a React component.
Constraints
Use a ref and call focus in useEffect.
Official Solution
import React, { useEffect, useRef, useState } from 'react';
export default function App() {
const inputRef = useRef(null);
const [value, setValue] = useState('');
useEffect(() => {
if (inputRef.current) inputRef.current.focus();
}, []);
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode quick search</h2>
<input ref={inputRef} value={value} onChange={(e) => setValue(e.target.value)} placeholder='Start typing...' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>Value: {value || '...'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!