useImperativeHandle
by Matt Tyson
HTML
<div id="root" />
CSS
input {
width: 200px;
border: 1px solid #ccc;
padding: 10px;
font-size: 16px;
}
button {
background-color: #42b983;
color: white;
border: none;
padding: 10px;
cursor: pointer;
margin: 10px;
}
div {
font-size: 20px;
margin-top: 10px;
font-family: Fira Code, Consolas, Source Code Pro, monospace;
}
React
const { useState, useRef, forwardRef, useImperativeHandle } = React;
const ChildComponent = forwardRef((props, ref) => {
const [count, setCount] = useState("");
const expound = () => {
setCount("The way that can be told is not the eternal way.");
};
useImperativeHandle(ref, () => ({
expound
}));
return (
<div>
<p>Count: {count}</p>
</div>
);
});
const App = () => {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.expound();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Expound</button>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<App />
);