Hello Everyone!
Today is Day 4 of my React learning journey, and I’m super excited because I completed my first mini project using React hooks!
This Mini Project About?
In this small project, I made a simple
Like/Dislike counter and a comment (command) boxwhere users can type something and submit it. The submitted commands are displayed as a list below.
Here’s what I used to build this:
- useState hook for managing state.
- onClick & onChange events to update the state when a user interacts with the buttons or textarea.
- JSX to render the UI based on the state.
Code Explanation (Step-by-Step)
1.useState Hook:
I used four pieces of state:
const [Like, setLike] = useState(0);
conconst [Like, setLike] = useState(0);
const [Dislike, setDislike] = useState(0);
const [command, setCommand] = useState("");
const [commandList, setCommandList] = useState([]);st [Dislike, setDislike] = useState(0);
const [command, setCommand] = useState("");
const [commandList, setCommandList] = useState([]);
-
LikeandDisliketo count the number of likes and dislikes. -
commandto store the text the user types in the textarea. -
commandListto store all the submitted commands as an array.
2.Like & Dislike Buttons:
<button onClick={() => setLike(Like + 1)}>Like</button>
<button onClick={() => setDislike(Dislike + 1)}>Dislike</button>
When the user clicks these buttons, the Like or Dislike count increases by 1 using the setLike or setDislike function.
3.Textarea & Command Submission:
<textarea
placeholder="Please command..."
onChange={(s) => setCommand(s.target.value)}>
</textarea>
- When the user types in the textarea, the
commandstate updates with the latest value.
<button onClick={() => setCommandList([...commandList, command])}>Submit</button>
- On clicking the Submit button, the current command is added to the
commandListarray using thespread operator(...).
4.Displaying the Commands:
<ul>
{commandList.map((s) => (
<li>{s}</li>
))}
</ul>
- The commandList array is looped using
.map()to display each command as a list item(<li>).
I Learned Today:
1.How to manage multiple state variables using useState.
2.Handling user input using onChange.
3.Updating lists in state using the spread operator (...).
4.Rendering dynamic lists using the map() function in JSX.
5.Building simple and interactive React components.
Challenges I Faced:
1.Forgetting to spread the old list while updating commandList. (Fixed by using [...commandList, command])
2.Understanding how onChange works with textarea — now it's clear!
React Docs – Using the State Hook (useState):
[(https://react.dev/learn/state-a-components-memory)]
The End!!
This mini project made me more confident in using hooks like useState. It also helped me understand how to capture user actions and display dynamic content in React.
"Mistakes make you a better coder."
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.