Listing 11-15: Getting the value of a textarea and counting its words
0 words.
import {useState,useRef} from 'react';
function WordCount(props){
const textAreaRef = useRef();
const [wordCount,setWordCount] = useState(0);
const countWords = (e) => {
const text = textAreaRef.current.value;
setWordCount(text.split(" ").length);
}
return (
<>
<textarea ref={textAreaRef} /><br />
<button onClick={countWords}>Count Words</button>
<p>{wordCount} words.</p>
</>
)
}
export default WordCount;
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.