This content originally appeared on DEV Community and was authored by Bhat Aasim
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! 🚀
This content originally appeared on DEV Community and was authored by Bhat Aasim
Bhat Aasim | Sciencx (2024-09-21T13:59:16+00:00) Why do React components need to start with capital letters?. Retrieved from https://www.scien.cx/2024/09/21/why-do-react-components-need-to-start-with-capital-letters/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.