name: react-ui-config-crash-fix
description: Fix "Cannot read properties of undefined (reading 'bg')" and similar crashes in React components when accessing dynamic config objects.
React UI Config Crash Fix
The Bug
In TypeScript React components, code like this crashes at runtime:
`typescript
const config = { active: { label: 'Ativo', bg: 'bg-success' }, inactive: { label: 'Inativo', bg: 'bg-muted' } };
const statusConfig = config[status]; // returns undefined if status is not in config
return
`
Root Cause
status, priority, channel, type etc. come from the database and can be undefined, null, or unexpected values not in the config map.
Fix 1: Default fallback (preferred)
`typescript
// Use explicit type for config
const statusConfig: Record
active: { label: 'Ativo', class: 'bg-success text-white' },
inactive: { label: 'Inativo', class: 'bg-muted text-muted-foreground' },
};
function getProjectStatus(project: { status?: string }) {
return statusConfig[project.status] ?? { label: project.status ?? 'Desconhecido', class: 'bg-muted text-muted-foreground' };
}
// In JSX:
{getProjectStatus(project).label}
`
Fix 2: Optional chaining (quick fix)
`typescript
`
Files Fixed in ComercialRS
| File | Bug | Fix |
| ------ | ----- | ----- |
src/components/tasks/TaskCard.tsx | priorityConfig[task.priority] undefined | Added ?? priorityConfig.medium fallback |
src/components/tasks/TaskViewDialog.tsx | Already had ?? channelConfig[m.channel] | OK |
src/pages/Notifications.tsx | typeConfig[notification.type] undefined | Added ?? typeConfig.info |
src/components/sales/MirrorHealthCard.tsx | statusConfig[status] undefined + missing error key | Added fallback + new error entry |
src/components/projects/ProjectDetailDialog.tsx | statusConfig[project.status] called twice | Created getProjectStatus() helper |
src/components/onboarding/OnboardingTutorial.tsx | channelConfig[ch] on map item | Needs ?? channelConfig[messages[0]] fallback |
Pattern to search for
When adding new config objects in React components, always search for potential undefined access:
`bash
Search for dangerous patterns
grep -rn "\[.\]\.bg\|\[.\]\.class\|\[.*\]\.label" src/
`
Safe pattern always has ?? fallback or optional chaining ?. after the bracket access.