DEV Community

SEENUVASAN P
SEENUVASAN P

Posted on

Day 13: Building a Counter with Input Functionality Using React

Today was my first real hands-on experience with React, and I’m excited to share what I learned and the simple project I built!

What I Learned Today

How to create a React component

How to use useState to manage dynamic variables (state)

How to handle user input and display it

How to build and update UI based on state changes
Enter fullscreen mode Exit fullscreen mode

My Simple React Project

To apply what I learned, I built a small project: a Counter App that can:

Increase, decrease, or reset a number

Accept a name from the user

Display the name after submission
Enter fullscreen mode Exit fullscreen mode

code:

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const [inputName, setInputName] = useState(""); // temporary input state
  const [name, setName] = useState(""); // stored name

  const handleSubmit = () => {
    setName(inputName); // store the input value
    setInputName("");   // optionally clear the input
  };

  return (
    <div className="container">
      <h1>Counter = {count}</h1>
      <button onClick={() => setCount(count + 1)}>Inc</button>
      <button onClick={() => setCount(count - 1)}>Dec</button>
      <button onClick={() => setCount(0)}>Reset</button>

      <div>
        <input
          type="text"
          value={inputName}
          onChange={(e) => setInputName(e.target.value)}
          placeholder="Enter name"
        />
        <button onClick={handleSubmit}>Submit</button>
      </div>

      {name && <h2>Stored Name: {name}</h2>}
    </div>
  );
Enter fullscreen mode Exit fullscreen mode

Output:

Image description
export default Counter;

Key Concepts I Used
React Component

I created a functional component called Counter, which is the building block of my app.

useState Hook

React’s useState helps me keep track of dynamic values like:

count: for the counter

inputName: the value being typed

name: the submitted and displayed name
Enter fullscreen mode Exit fullscreen mode

Event Handling

The onClick handlers update the state using setCount() and setName().

The onChange event tracks the text input in real-time.
Enter fullscreen mode Exit fullscreen mode

What’s Next?

Now that I’ve done this project, I’m planning to:

Add some basic CSS styles

Learn about props and pass data between components

Try React Router to build multiple pages

Use conditional rendering for better user experience
Enter fullscreen mode Exit fullscreen mode

Top comments (0)