Avoiding Reserved Keywords as React Component Names
Using JavaScript reserved keywords as component names can cause syntax errors and unexpected behavior. Here’s how to handle this properly:
Common Problematic Component Names
Reserved Keywords to Avoid:
class
→ UseClassName
,ClassList
, orClassComponent
insteadswitch
→ UseSwitchCase
,ToggleSwitch
, orSwitcher
for
→ UseForm
,ForLoop
, orLabelFor
function
→ UseFunctionComponent
orFunc
new
→ UseNewItem
,CreateNew
, orFreshComponent
Solutions and Best Practices
1. Renaming Components (Recommended)
// Bad
function class(props) {
return <div {...props} />;
}
// Good
function ClassComponent(props) {
return <div {...props} />;
}
2. Using Aliases When Necessary
// If you must reference the keyword
const SwitchComponent = Switch;
function MyComponent() {
return (
<SwitchComponent>
{/* cases */}
</SwitchComponent>
);
}
3. Proper Naming Conventions
Follow these patterns instead:
- Add “Component” suffix:
ClassComponent
- Use domain-specific prefixes:
UiSwitch
,FormFor
- Be more descriptive:
CourseClass
instead ofClass
Common Scenarios and Fixes
1. For “class” Keyword
// Bad
const class = ({ children }) => <div className="wrapper">{children}</div>;
// Good solutions:
const ClassWrapper = ({ children }) => <div className="wrapper">{children}</div>;
// or
const Div = ({ children }) => <div className="wrapper">{children}</div>;
2. For “switch” Keyword
// Bad
const switch = ({ value, cases }) => cases[value] || cases.default;
// Good
const SwitchRenderer = ({ value, cases }) => cases[value] || cases.default;
// or
const CaseSwitch = ({ value, cases }) => cases[value] || cases.default;
3. For “function” Keyword
// Bad
const function = ({ args, body }) => (
<div>
<pre>function({args}) {'{'}{body}{'}'}</pre>
</div>
);
// Good
const FunctionDeclaration = ({ args, body }) => (
<div>
<pre>function({args}) {'{'}{body}{'}'}</pre>
</div>
);
ESLint Rules to Prevent Issues
Add to your .eslintrc.js
:
{
"rules": {
"no-restricted-syntax": [
"error",
{
"selector": "VariableDeclarator[id.name=/^(class|switch|function|new|for)$/]",
"message": "Avoid using reserved keywords as component names"
}
]
}
}
When Working with Third-Party Libraries
Some libraries might use reserved keywords in their APIs. In these cases:
- Use renaming imports:
import { switch as Switch } from 'some-library';
- Or wrap them:
function MySwitch(props) {
return <Switch {...props} />;
}
TypeScript Considerations
TypeScript will flag these issues more aggressively. The solutions are the same, but you’ll get immediate feedback during development.
Remember: Choosing clear, descriptive names that don’t conflict with JavaScript syntax will make your code more maintainable and prevent subtle bugs. Always prefer semantic naming over brevity when naming components.