React Word Counter - JavaScript Exercise #16
Build a React Word Counter Component
Overview
In this exercise, you will create a React component that allows the user to input a text and displays the number of words in the text.
Instructions
Create a new component called
WordCounter
in a new file.The component should have a textarea where the user can input a text.
Display the number of words in the text below the textarea.
The number of words should update in real time as the user types.
Use state to keep track of the number of words.
Use the built-in JavaScript string method "split" to split the text into an array of words, then count the number of elements in the array.
Bonus Requirements
Add a button that clears the textarea and resets the word count.
Add a feature that allows the user to input a maximum number of words and displays a warning message if they exceed the limit.
Use a different method to count the number of words (e.g., regular expressions).
Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.
So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Word Counter exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.
Output for the Word Counter exercise
import React, { useState } from 'react';
const WordCounter = () => {
const [text, setText] = useState('');
const [wordCount, setWordCount] = useState(0);
const [maxWords, setMaxWords] = useState('');
const handleInputChange = (e) => {
const newText = e.target.value;
const newWordCount = newText.trim().split(/\s+/).filter(Boolean).length;
setWordCount(newWordCount);
setText(newText);
};
const handleClearClick = () => {
setText('');
setWordCount(0);
};
const handleMaxWordsChange = (e) => {
const newMaxWords = e.target.value;
setMaxWords(newMaxWords);
if (newMaxWords && wordCount > parseInt(newMaxWords)) {
setWordCount(parseInt(newMaxWords));
}
};
return (
<div>
<textarea value={text} onChange={handleInputChange} />
<div>
Word count: {wordCount}
{maxWords && ` / ${maxWords} max`}
</div>
<div>
<label>
Max words:
<input type="number" value={maxWords} onChange={handleMaxWordsChange} />
</label>
</div>
<button onClick={handleClearClick}>Clear</button>
</div>
);
};
export default WordCounter;
import React from 'react';
import WordCounter from './WordCounter';
const App = () => {
return (
<div>
<h1>React Word Counter</h1>
<WordCounter />
</div>
);
};
export default App;
Few examples of applications where the WordCounter
component could be useful:
Blog post editor: When writing blog posts, it's often helpful to know the length of your article to ensure it fits within certain length constraints. By including the
WordCounter
component in the blog post editor, the author can easily keep track of the number of words in their article as they write, and ensure they stay within their desired word count.Social media post editor: Similar to the blog post editor, the
WordCounter
component could also be used in social media post editors. For example, Twitter has a maximum tweet length of 280 characters, which can roughly translate to about 50 words. Including theWordCounter
component in the tweet editor can help users ensure their tweets stay within the character limit.Language learning app: Language learners often need to practice writing in their target language, and it can be helpful for them to receive feedback on their writing length. By including the
WordCounter
component in a language learning app's writing exercises, learners can receive immediate feedback on the length of their writing and track their progress over time.Job application form: When applying for jobs, candidates may need to provide a written response to a prompt or answer essay questions. The
WordCounter
component can help candidates ensure they are meeting the specified word count requirements and prevent them from accidentally going over the word limit.
These are just a few examples, but there are many more use cases where the WordCounter
component can come in handy!
In this exercise, we created a WordCounter
component using React that allows users to input text and tracks the number of words in the input. We also added a bonus feature that allows users to set a maximum number of words and displays the current word count relative to the maximum. We then discussed several potential applications for the WordCounter
component, such as in blog post and social media editors, language learning apps, and job application forms.
React provides a powerful and flexible way to create reusable components and the WordCounter
component is just one example of how we can use React to create useful tools and applications. Whether you're a beginner or an experienced React developer, I hope this exercise has provided some insights into how we can use React to build user interfaces and solve real-world problems.
Thanks for taking this JavaScript exercise!
I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!
If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.
And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.