Why do React components need 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?
// it's wrong and will not work
export function myComponent() {
return (
<h1>Hello, World!</h1>
);
}
// it's correct rule of 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.
Software Engineer at FTS
5 个月Useful tips