Listing 11-16: Customizing a value exposed by a ref
import {useState,useRef,useImperativeHandle,forwardRef} from 'react';
const CountingBox = forwardRef((props, ref) => {
const [text,setText] = useState('');
useImperativeHandle(ref, () => {
return {count: text.split(" ").length}
},[text]);
return (
<>
<textarea value={text} onChange={(e)=>setText(e.target.value)} />
</>);
});
function TextEdit(props){
const countingBoxRef = useRef();
const [wordCount,setWordCount] = useState(0);
const handleClick = (count) => {
setWordCount(count)
}
return (
<>
<CountingBox ref={countingBoxRef} /><br />
<button onClick={()=>handleClick(countingBoxRef.current.count)}>count words</button><br />
current count: {wordCount}<br />
</>
)
}
export default TextEdit;
current count: 0
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.