Forward Ref Input Focus
ReactJS
Hard
7 views
Problem Description
Build an input component that exposes focus() using forwardRef.
Output Format
Render a React component.
Constraints
Use forwardRef and pass the ref to the input element.
Official Solution
import React, { forwardRef, useRef } from 'react';
export const TextInput = forwardRef(function TextInput({ value, onChange, placeholder }, ref) {
return (
<input
ref={ref}
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
style={{ padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb', width: 320 }}
/>
);
});
export default function App() {
const inputRef = useRef(null);
const [text, setText] = React.useState('');
return (
<div style={{ padding: 16 }}>
<TextInput ref={inputRef} value={text} onChange={setText} placeholder='Search meetcode' />
<div style={{ marginTop: 10 }}>
<button type='button' onClick={() => inputRef.current && inputRef.current.focus()} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
Focus input
</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!