ReactJS Program to Class Component Counter with Explanation
ReactJS
Medium
State Management
22 views
1 min read
81 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around component, class, counter. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create a small counter using a class component (for practice).
Input Format
No input.
Output Format
Render a React component.
Constraints
Use setState correctly.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React from 'react';
class Counter extends React.Component {
state = { count: 0 };
render() {
return (
<div style={{ padding: 16 }}>
<strong>meetcode</strong>
<div style={{ marginTop: 8 }}>Count: {this.state.count}</div>
<button
type='button'
onClick={() => this.setState((s) => ({ count: s.count + 1 }))}
style={{ marginTop: 10, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}
>
Add
</button>
</div>
);
}
}
export default function App() {
return <Counter />;
}
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create a small counter using a class component (for practice).
Input / Output
Output
Render a React component.
Constraints
Use setState correctly.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Difficulty
Medium
ReactJS
Official Solution
import React from 'react';
class Counter extends React.Component {
state = { count: 0 };
render() {
return (
<div style={{ padding: 16 }}>
<strong>meetcode</strong>
<div style={{ marginTop: 8 }}>Count: {this.state.count}</div>
<button
type='button'
onClick={() => this.setState((s) => ({ count: s.count + 1 }))}
style={{ marginTop: 10, padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}
>
Add
</button>
</div>
);
}
}
export default function App() {
return <Counter />;
}
Solutions (0)
No solutions submitted yet. Be the first!