Learnitweb

Why React component names must start with an uppercase letter?

In React, component names must start with an uppercase letter due to how JSX differentiates between HTML elements and custom components.

Reasons for Capitalizing React Component Names

JSX Differentiation

  • JSX treats lowercase names (<div>, <span>, etc.) as native HTML elements.
  • JSX treats uppercase names (<MyComponent>) as custom React components.
function myComponent() {
  return <h1>Hello</h1>;
}
export default myComponent;

// This will throw an error because 'myComponent' is treated as an HTML tag
<myComponent />

JSX Compiles to React.createElement()

  • When JSX is transpiled, React uses React.createElement().
  • If a component starts with lowercase, React assumes it’s an HTML tag instead of a component.

Example of JSX compilation:

<MyComponent />

Compiles to:

React.createElement(MyComponent);

But if it were <myComponent />, React would assume it’s an HTML tag, which doesn’t exist.

Code Readability and Best Practices

  • Uppercase naming clearly differentiates React components from normal HTML elements.
  • It aligns with JavaScript’s convention where class names start with uppercase (PascalCase).