Why do React component needs to start with capital letters?

September 21, 2024 (2mo ago)

React Components should start with Capital Letter

Why do React components need to start with capital letters?

If you’ve ever worked with React, you might have noticed that component names always start with capital letters. But do you know why? 🤔

//This is wrong and will not work ❌
export function myComponent() {
  return (
        <h1>Hello, World!</h1>
    );
}
//Right way to write a React component ✅
export function MyComponent() {
  return (
        <h1>Hello, World!</h1>
    );
}

In JSX, React components are written in a syntax that gets transformed into plain JavaScript using the React.createElement API, thanks to Babel. Here’s where the capital letter comes in:

When Babel encounters a name starting with a capital letter, it knows it’s dealing with a React component and converts it into a React Fiber object (a key part of React’s rendering system).

On the other hand, if the name starts with a lowercase letter, Babel treats it as a string rather than a component. This helps React differentiate between native HTML elements and custom components!

So, always remember to capitalize your component names for React to interpret them correctly. 💡

Thanks for reading! 🚀