Click files to view code ā
Build an interactive counter component that allows users to increment, decrement, and reset a numerical value. This component should display the current count and provide three buttons for user interaction.
[!TIP] Goal
Use React's
useState[!IMPORTANT] Requirements
useStateNo external dependencies needed - this can be built with vanilla React.
Key Topics:
useStatePlan of Action:
CounteruseState(0)incrementdecrementresetimport React, { useState } from 'react';
import './Counter.css';
function Counter() {
// Initialize state with default value of 0
const [count, setCount] = useState(0);
// Handler functions
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
const reset = () => {
setCount(0);
};
return (
<div className="counter-container">
<h2>Counter Component</h2>
<div className="counter-display">
<h1>{count}</h1>
</div>
<div className="counter-buttons">
<button onClick={decrement} className="btn btn-decrement">
- Decrement
</button>
<button onClick={reset} className="btn btn-reset">
Reset
</button>
<button onClick={increment} className="btn btn-increment">
+ Increment
</button>
</div>
</div>
);
}
export default Counter;CSS Styling (Counter.css):
.counter-container {
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem;
font-family: Arial, sans-serif;
}
.counter-display {
margin: 2rem 0;
padding: 2rem;
background-color: #f0f0f0;
border-radius: 10px;
min-width: 200px;
text-align: center;
}
.counter-display h1 {
margin: 0;
font-size: 4rem;
color: #333;
}
.counter-buttons {
display: flex;
gap: 1rem;
}
.btn {
padding: 0.75rem 1.5rem;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
transition: transform 0.1s, box-shadow 0.2s;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.btn:active {
transform: translateY(0);
}
.btn-increment {
background-color: #4caf50;
color: white;
}
// ...Best Practices:
setCount(prevCount => prevCount + 1)Common Pitfalls:
count++useStateEnhancements:
Example with Functional Updates:
const increment = () => {
setCount(prevCount => prevCount + 1);
};
const decrement = () => {
setCount(prevCount => prevCount - 1);
};Example with Props for Initial Value:
function Counter({ initialValue = 0 }) {
const [count, setCount] = useState(initialValue);
// ... rest of the code
}Testing Considerations:
This counter component serves as a foundational exercise for understanding React state management and forms the basis for more complex interactive components.
No files open
Click a file in the explorer to view