Building a React Application with a Paragraph Toggle

Building a React Application with a Paragraph Toggle

Hello guys, today we're going to create a simple toggle application in React. This application will toggle a paragraph by clicking a button.

Prerequisite

  • Familiarity with JS

  • React Fundamentals (Components , useState and useEffect).

Installation

It is super easy to create react application by using Vite. To create application you have to use below command

npm create vite@latest

hit enter after this command, you’ll be getting few prompts to enter project details as below images

Enter project name and select framework as React

Select variant as JavaScript:

After this do installation using below commands

Now do npm run dev to start the project.

Folder Structure

The folder structure of our will look like this:

Components

Now create 2 folders inside the src folder: one for components and one for hooks.

In the hooks folder, we'll create a useToggle hook. The reason for creating a custom hook is that if we want to use it elsewhere in the code later, it can be done easily, making the code more readable and extendable.

Our hook will look like this:

This useToggle hook will take one argument, which is the initial value for the toggle. We set the default value to true because we want the paragraph to be visible by default. It will have a state variable, toggle, and a setter function to update the toggle's state.

To manage the toggle functionality, we'll create a handleToggle function. This function will call the setter function to change the boolean value based on its previous state.

The final UI looks like this:

Conclusion

I hope you find this article helpful and that it adds value to your coding career.
If you want, you can add more features to this app, like decrementing the count or adding a light/dark theme.
You can check out the full source code here 👈

If you have any suggestions, ideas, or questions, please reach out to me on my social media.

Until next time, happy coding!

Did you find this article valuable?

Support Vasant Mestry by becoming a sponsor. Any amount is appreciated!