ReactJS Program to Intl Formatter Outside Component with Explanation
ReactJS
Easy
Performance & Patterns
31 views
1 min read
87 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around intl, component, formatter. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create expensive Intl formatter once, not every render.
Input Format
No input.
Output Format
Render a React component.
Constraints
Move heavy objects (Intl/regex/maps) outside components when possible.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react';
const money = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
export default function App() {
const [price, setPrice] = useState('199');
const n = Number(price);
const safe = Number.isFinite(n) ? n : 0;
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode pricing</h2>
<input value={price} onChange={(e) => setPrice(e.target.value.replace(/\\D/g, ''))} inputMode='numeric' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>Formatted: {money.format(safe)}</div>
</div>
);
}
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 expensive Intl formatter once, not every render.
Input / Output
Output
Render a React component.
Constraints
Move heavy objects (Intl/regex/maps) outside components when possible.
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).
Official Solution
import React, { useState } from 'react';
const money = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
export default function App() {
const [price, setPrice] = useState('199');
const n = Number(price);
const safe = Number.isFinite(n) ? n : 0;
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode pricing</h2>
<input value={price} onChange={(e) => setPrice(e.target.value.replace(/\\D/g, ''))} inputMode='numeric' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>Formatted: {money.format(safe)}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!