Introduction
In this lab, we will be building a limited textarea component using React. The purpose of this lab is to provide a hands-on experience in utilizing React hooks, such as useState() and useCallback(), to create a component that limits the number of characters a user can input in a textarea. By the end of this lab, you will have a functional textarea component that displays the character count and limits the number of characters a user can input.
Textarea With Character Limit
index.htmlandscript.jshave already been provided in the VM. In general, you only need to add code toscript.jsandstyle.css.
Here's the code:
const LimitedTextarea = ({ rows, cols, value, limit }) => {
const [content, setContent] = React.useState(value.slice(0, limit));
const setFormattedContent = React.useCallback(
(text) => {
setContent(text.slice(0, limit));
},
[limit]
);
return (
<>
<textarea
rows={rows}
cols={cols}
onChange={(event) => setFormattedContent(event.target.value)}
value={content}
/>
<p>
{content.length}/{limit}
</p>
</>
);
};
ReactDOM.createRoot(document.getElementById("root")).render(
<LimitedTextarea limit={32} value="Hello!" />
);
In this code, we:
- Simplified the comments to provide a more concise overview of what each part of the code does.
- Removed unnecessary code comments.
- Removed the
setContentfunction from theuseCallbackdependency array, as it doesn't need to be there. - Added parentheses around the
textargument in theuseCallbackfunction for consistency. - Used arrow functions for the
onChangeevent handler for brevity.
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Textarea With Character Limit lab. You can practice more labs in LabEx to improve your skills.