Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does "import { React } from 'react';" not work? [duplicate]

Can anyone explain to me why

import { React } from 'react';

breaks everything, yet

import React from 'react';

works just fine? Aren't they saying the same thing? I've tried to find an answer elsewhere in documentation and on the internet, but I can't figure it out. I think it may have something to do with Babel?

Here are my npm packages if it helps:

"dependencies": {
    "moment": "^2.18.1",
    "prop-types": "^15.5.10",
    "react": "^15.5.4",
    "react-dom": "^15.5.4",
    "react-router-dom": "^4.0.0",
    "styled-jsx": "^3.2.1",
    "uuid": "^3.2.1"
  },
  "devDependencies": {
    "babel-core": "^6.24.1",
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "eslint": "^4.13.1",
    "eslint-loader": "^1.9.0",
    "eslint-plugin-react": "^7.5.1",
    "file-loader": "^1.1.6",
    "html-webpack-plugin": "^2.29.0",
    "react-hot-loader": "^3.0.0-beta.7",
    "url-loader": "^0.6.2",
    "webpack": "^3.4.0",
    "webpack-dev-server": "^2.5.0"
}
like image 421
glitchwizard Avatar asked Oct 16 '25 12:10

glitchwizard


1 Answers

import React from 'react'

This essentially says "find the default export from the react module and import that as a constant that I want to call React."

import { React } from 'react'

This says "find the export from the react module which is explicitly named React, and import that here as a constant that I want to call React."

Why doesn't import { React } from 'react' work?

Because there isn't an export named React in the react package. There is only a single default export. If you do this, you'll find that React is undefined.

But it doesn't even look like I use React in my code. So, couldn't I just name it anything I want, like import Foobar from 'react'?

No, sorry. You need to import the default and 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 React.


Helpful references:

  • ES6 syntax and usage of import
like image 73
Alvin S. Lee Avatar answered Oct 19 '25 02:10

Alvin S. Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!