Counter application with react and typescript

suhakim

sadiul hakim

Posted on November 13, 2021

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!

💖 💪 🙅 🚩
suhakim
sadiul hakim

Posted on November 13, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related