Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import doesn't work when name doesn't start with capital letter

After transpiling this code doesn't work

import React from 'react';
import ReactDOM from 'react-dom';
import firstLow from './moniesApp.js';

ReactDOM.render(<firstLow />, document.getElementById('content'));

but this does

import React from 'react';
import ReactDOM from 'react-dom';
import FirstHigh from './moniesApp.js';

ReactDOM.render(<FirstHigh />, document.getElementById('content'));

in first case babel produces

_reactDom2.default.render(_react2.default.createElement('firstLow', null), document...

and on page there is an empty <firstLow data-reactroot><firstLow/> element rendered.

And in second case

_reactDom2.default.render(_react2.default.createElement(_moniesApp2.default, null), document...

and it works. My component is rendered.

What's going on?

like image 940
Piotr Perak Avatar asked Oct 26 '16 21:10

Piotr Perak


People also ask

Why should Component names start with capital letters?

All React component names must start with a capital letter. If you start a component name with a lowercase letter, it will be treated like a built-in element like a <div> or a <span> . This is because of the way JSX works. In JSX, rendering a component that begins with a lowercase letter compiles down to React.

Can React component name start with number?

No. JavaScript variables cannot begin with numbers. Show activity on this post.

What are the limitations of React?

Disadvantage of ReactJSThey need to be always updated with their skills and learn new ways of doing things. It is another cons which are common for constantly updating technologies. React technologies updating and accelerating so fast that there is no time to make proper documentation.

What is a common use case for ref?

There are a few good use cases for refs: Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries.


2 Answers

What's going on?

This is a convention in JSX/React. Lower case names are converted to strings (tags), capitalized names are resolved as variables (components).

From the docs:

Caveat:

Always start component names with a capital letter.

For example, <div /> represents a DOM tag, but <Welcome /> represents a component and requires Welcome to be in scope.

like image 189
Felix Kling Avatar answered Oct 06 '22 14:10

Felix Kling


In React, Component names start with capital letters. Lower-case JSX tags represent literal HTML tags. This is part of the React specification.

This is why <foo> is translated to createElement('foo'), while <Foo> yields createElement(module.Foo).

You should name your components with capital letters. Not much else to do.

like image 26
slezica Avatar answered Oct 06 '22 15:10

slezica