Last active: a year ago
useImperativeHandle with typescript
import { css } from "@emotion/css";
import { forwardRef, useImperativeHandle, useRef } from "react";
type Props = {
placeholder?: string;
};
export type ImpertiveHandler = {
focus: () => void;
};
const Child = forwardRef<ImpertiveHandler, Props>(({ placeholder }, ref) => {
const inputRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current?.focus();
}
}));
return (
<>
<input
ref={inputRef}
className={css`
border: gray solid 1px;
border-radius: 6px;
padding: 0.5rem;
transition: all 0.3s ease-in-out;
width: 250px;
`}
placeholder={placeholder}
type="text"
/>
</>
);
});
export default Child;
import "./styles.css";
import Child, { ImpertiveHandler } from "./Child";
import { css } from "@emotion/css";
import { useRef } from "react";
export default function App() {
const inputRef = useRef<ImpertiveHandler>(null);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<div
className={css`
display: flex;
justify-content: center;
flex-flow: column;
align-items: center;
`}
>
<button
className={css`
padding: 9px 15px;
border-radius: 8px;
border: gray solid 1px;
background-color: #fff;
margin-bottom: 1rem;
&:active {
background-color: gray;
}
`}
onClick={() => inputRef.current?.focus()}
>
Focus input
</button>
<Child ref={inputRef} placeholder="Hi, there" />
</div>
</div>
);
}