counter
Here's a simple React TypeScript functional component that implements a counter with increment, decrement, and reset functionality:
import React, { useState } from 'react';
const CounterApp: React.FC = () => {
const [count, setCount] = useState<number>(0);
const increment = () => setCount(prevCount => prevCount + 1);
const decrement = () => setCount(prevCount => prevCount - 1);
const reset = () => setCount(0);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement} disabled={count === 0}>Decrement</button>
<button onClick={reset} disabled={count === 0}>Reset</button>
</div>
);
};
export default CounterApp;
In this code:
- We use the
useState
hook to create acount
state variable initialized to0
. - Three functions
increment
,decrement
, andreset
are defined to change the state accordingly. - The
increment
function increases thecount
by 1. - The
decrement
function decreases thecount
by 1, but only ifcount
is greater than0
. - The
reset
function sets thecount
back to0
. - We render the
count
and three buttons that call the respective functions when clicked. - The
decrement
andreset
buttons are disabled when thecount
is0
to prevent negative numbers or unnecessary resets.