React components needs to start with capital letters
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?
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).
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>
);
}
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!
Why?
Babel interpreted in different ways:
React.createElement('div');
// Interpreted as a native HTML <div> element
React.createElement(MyComponent);
// Interpreted as a custom React component
If MyComponent is written in lower case (myComponent), React will look for a native HTML element <myComponent>
which doesn't exists, causing the app to fail.