DEV Community

sadiul hakim
sadiul hakim

Posted on

3 1

Counter application with react and typescript

Let's build this counter application using react-typescript.We are going to use useReducer hook for this application.

This is a counter application picture

Let's set up our application

$ cd Desktop
$ mkdir react-counter
$ cd react-counter
Enter fullscreen mode Exit fullscreen mode

Now create a react app

$ npx create-react-app ./ --template typescript
Enter fullscreen mode Exit fullscreen mode

You should see a brand new react application.Clean up all unnecessary files.You can use a different component but in my case i am going to use App.tsx component.

At first create a component App and export it defaultly

const App:React.FunctionComponent=()=>{
  return <div className='container'></div>
}
Enter fullscreen mode Exit fullscreen mode

Now we are going to setup our useReducer hooks.Add this statement to your code

const [state, dispatch] = React.useReducer(counterReducer, initialState);
Enter fullscreen mode Exit fullscreen mode

Now let's create our cunterReducer and initialState

First initialState..

const initialState = {
  count: 0,
};
Enter fullscreen mode Exit fullscreen mode

And then counterReducer

type ActionsType = {
  type: string;
  payload?: number;
};

const counterReducer = (
  state: typeof initialState,
  action: ActionsType
): State => {

};
Enter fullscreen mode Exit fullscreen mode

Now let's add some actionTypes and actionCreators

ActionTypes..

const INCREMENT = "INCREMENT";
const DECREMENT = "DECREMENT";
const RESET = "RESET";
Enter fullscreen mode Exit fullscreen mode

and actionCreators..


const increment = (value: number) => {
  return {
    type: INCREMENT,
    payload: value,
  };
};

const decrement = (value: number) => {
  return {
    type: DECREMENT,
    payload: value,
  };
};

const reset = () => {
  return {
    type: RESET,
  };
};

Enter fullscreen mode Exit fullscreen mode

Yeah i am using redux pattern.Now let's add some logic to our reducer.

 switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + Number(action.payload) };
    case DECREMENT:
      return { ...state, count: state.count -Number(action.payload) };
    case RESET:
      return { ...state, count: 0 };
    default:
      return state;
  }
Enter fullscreen mode Exit fullscreen mode

Now let's add some jsx to our application

<div className="container">
      <p>{state.count}</p>
      <div className="wrapper">
        <button onClick={() => dispatch(increment(2))}>increment</button>
        <button onClick={() => dispatch(decrement(2))}>decrement</button>
        <button onClick={() => dispatch(reset())}>reset</button>
      </div>
<div>
Enter fullscreen mode Exit fullscreen mode

If you want those styles you can add these css code in index.css file

p {
  font-size: 2rem;
  font-weight: 600;
}
button {
  background: #004567;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 20px;
  margin: 10px;
  font-size: 1.2rem;
  text-transform: capitalize;
}
.container {
  width: 500px;
  margin: 100px auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

Enter fullscreen mode Exit fullscreen mode

If you start your application you should see something on the screen a simple counter application working.

Now add a input element to add numbers randomly..

<input type="number" name="count" value={value} onChange={handleChange}/><button onClick={() = dispatch(increment(value as number))}>
       add
</button>
Enter fullscreen mode Exit fullscreen mode

Now where do i get those value={value} and onChnage={handleChange} for that add following code at top of your component

const [value, setValue] = React.useState<number>();
Enter fullscreen mode Exit fullscreen mode

and change handler handleChange

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(Number(e.target.value));
  };
Enter fullscreen mode Exit fullscreen mode

you should keep all hooks at the top then functions

Now add these css code for your input element

input {
  padding: 10px;
  width: 300px;
}
Enter fullscreen mode Exit fullscreen mode

Now if you got to your browser and refresh if it is needed,you should see same counter application as i have shown you at the top.Try to click buttons and check if it is working.

Thank you for being with me so long.See you.Bye!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay