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
useStatehook to create acountstate variable initialized to0. - Three functions
increment,decrement, andresetare defined to change the state accordingly. - The
incrementfunction increases thecountby 1. - The
decrementfunction decreases thecountby 1, but only ifcountis greater than0. - The
resetfunction sets thecountback to0. - We render the
countand three buttons that call the respective functions when clicked. - The
decrementandresetbuttons are disabled when thecountis0to prevent negative numbers or unnecessary resets.