Why a React component need to start with Uppercase letter in JSX?

Hi, in this post we are going to know why a React component need to start with Uppercase letter in JSX syntax.

So, if we use React API to create the elements then we are going to use the React.createElement() method that accept 3 parameters first is the type (could be a tag name in string, component or fragment) the second parameter are the props { } then the final is the children.

Note: you can omit the props and this will be null.

React.createElement(
  type,
  [props],
  [...children]
)

If we convert that code will be like this:

<div>children</div>

Ok, if we have a function that will render a custom component:

const message = ({children}) => {
      return <div className="message">{children}</div>
    }

Then we can pass that function into the React.createElement() method as first parameter:

    const helloElement = React.createElement(message, {
      children: 'Hello world',
    })

Ok cool, then let’s render the <message>Hello world</message> directly like this:

<div className="container">
   <message>Hellow world</message>
   {React.createElement(message, {children: 'Goodby world'})}
</div>

Then the <message> will not include the class.

And also the browser is giving us a warning message:

Let’s see how babel compiled the last code, so the <message>Hellow world</message> is compiled in double quotes then the next element is created without quotes (passed as a reference to the function message()), so we need to have some mechanism to tell Babel “that instead of insert quotes we need to pass that as a reference to the function message()

So, what we need to do is just what the console warning say:

Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

So, let modify the function name with Uppercase and call that as <Message>…</Message>

   const Message = ({children}) => {
      return <div className="message">{children}</div>
    }

    const element = (
      <div className="container">
        <Message>Hellow world</Message>
        {React.createElement(Message, {children: 'Goodby world'})}
      </div>
    )

And with this way the warning console disappear and the DOM is:

And the Babel compiled code is now how need to be (Message as reference to the function Message())

So, the JSX syntax specifications says that is you start with an angle bracket and you provide a React element type as a capital letter that means that it should be a reference to the variable that is in the scope.

JSX is a really nice declarative clean API for creating UI so we don’t need to use React.createElement, etc.

By Cristina Rojas.