Using reserved JavaScript keywords as component names

Loading

A common mistake in React is using JavaScript reserved keywords as component names, which can cause syntax errors or unexpected behavior. Here’s what you need to know:

Problematic Component Names

These JavaScript keywords cannot be used as component names:

// ❌ All of these will cause errors
function switch() { return <div>...</div> }  // Reserved keyword
function class() { return <div>...</div> }   // Reserved keyword
function delete() { return <div>...</div> }  // Reserved keyword
function new() { return <div>...</div> }     // Reserved keyword

Why This Is a Problem

JavaScript reserves certain words for language features. When you try to use them as identifiers:

  • Modern IDEs will immediately flag them as syntax errors
  • Your code won’t compile
  • Even if it somehow runs, you’ll get unpredictable behavior

Solutions

1. Add a Prefix/Suffix

The most common solution is to modify the name slightly:

// ✅ Good alternatives
function SwitchComponent() { return <div>...</div> }
function ClassView() { return <div>...</div> }
function DeleteButton() { return <div>...</div> }
function NewItemForm() { return <div>...</div> }

2. Use Different Synonyms

Choose a different word with similar meaning:

// ✅ Semantic alternatives
function Toggle() { return <div>...</div> }  // instead of 'switch'
function Category() { return <div>...</div> } // instead of 'class'
function Remove() { return <div>...</div> }   // instead of 'delete'

3. For HTML Elements That Conflict

Some HTML elements share names with JS keywords. For these, use capitalization:

// ✅ Capitalized version
function Label(props) { return <label {...props} /> }  // 'label' is both HTML and JS keyword

Special Case: “class” Prop

When dealing with the HTML class attribute (a reserved keyword), React uses className:

// ❌ Wrong
<div class="my-class">...</div>

// ✅ Correct
<div className="my-class">...</div>

Complete List of Reserved Keywords to Avoid

These JavaScript keywords should never be used as component names:

abstract, arguments, await, boolean, break, byte, case, catch, char, class, 
const, continue, debugger, default, delete, do, double, else, enum, eval, 
export, extends, false, final, finally, float, for, function, goto, if, implements, 
import, in, instanceof, int, interface, let, long, native, new, null, package, 
private, protected, public, return, short, static, super, switch, synchronized, 
this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with, yield

Best Practices

  1. Always capitalize component names (required by JSX anyway)
  2. Use descriptive names that indicate the component’s purpose
  3. Add suffixes like “Component”, “View”, or “Container” when needed
  4. Check for conflicts if your linter doesn’t catch them

Leave a Reply

Your email address will not be published. Required fields are marked *