Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing React and ReactDOM

When importing react and reactDOM I have always seen:

import React from 'react';
import ReactDOM from 'react-dom';

Can I name React and ReactDOM something else?

like image 379
tausabao Avatar asked Mar 13 '19 01:03

tausabao


1 Answers

React

For React, you must import React from 'react'. You need to import the default, and you need to name it React. This is because anytime you write JSX code like <MyComponent /> or <App />, this JSX code is transpiled and uses React.createElement(). So, you need to have access to the React object as it is named.

ReactDOM

For ReactDOM, however, you are probably mostly concerned with the DOM-related methods that are part of the default export, methods like render() or hydrate(). Because that's what you'll probably be using, you can name your import module anything you want. So, you could do something like this:

import FooBar from 'react-dom'
FooBar.render(someElement)

This does work, but the standard convention is to call the imported module ReactDOM, as that would make your code more understandable to anyone else looking at it.


Additional resources:

  • ES6 syntax and usage of import
  • Babel tranform of JSX requires React
  • ReactDOM documentation
like image 140
Alvin S. Lee Avatar answered Sep 29 '22 11:09

Alvin S. Lee