Import react from react ошибка

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"
}

Смотрю курс 2020 года по React и там когда человек делал один из компонентов, у него вышла ошибка и нужно было прописать:
import React from 'react';
Но в то же время я когда этого не прописал, все работало.
Как я понял было обновление и убрали надобность добавления? Или все же лучше на всякий случай прописывать в коде:
import React from 'react';


  • Вопрос задан

    более двух лет назад

  • 1335 просмотров

если не используются какие-нибудь хуки например useStateили useEffect то можно и не подключать

Пригласить эксперта

Скорее всего у вас React подгружен на HTML странице (как на картинке ниже), в этом случае не нужно импортировать как модуль.
6017f0c6ecbf7161788867.png
Другой способ подключения это установить библиотеку react через npm и импортировать его в коде.
import React from 'react';
Про это все написано в доках React, советую их смотреть, а не ролики, тем более там есть русский язык.


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

Hi, I checked the code and tried to reproduce the scenario but it didn’t give any error so went and checked the code provided in the first post.

So, the problem here is when you remove the react imports then you need to de-structure and then import the react functions as an object.

image

`import React from «react»;
import ReactDOM from «react-dom»;

import App from «./App»;

const rootElement = document.getElementById(«root»);
ReactDOM.render(
<React.StrictMode>

</React.StrictMode>,
rootElement
);`

So, after you remove the react import statement then you have to remove the React. syntax from the code else the JSX compiler will not read the react code.
So, after removing the import the code should be changed to below:

image

`import {StrictMode} from «react»;
import ReactDOM from «react-dom»;

import App from «./App»;

const rootElement = document.getElementById(«root»);
ReactDOM.render(

,
rootElement
);
`
Just a Note: It’s not necessary to import react but the useEffect, useState, StrictMode needs to be imported .

If you use React, import React from 'react' is the first thing that you write in your code but if you have created a new react app using creat-react-app recently, you might have noticed that there is no import React statement at the top and your code works just fine. So, How’s that working?

Well, previously you had to import React because the JSX is converted into regular Javascript that use react’s React.createElement method.
JSX conversion
But, React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX without using React.createElement. This allows us to not import React, however, you’ll need to import React to use Hooks and other exports that React provides. But if you have a simple component, you no longer need to import React. All the JSX conversion is handled by React without you having to import or add anything.

This new JSX transform is also supported in older versions of React so you can start using them even if you don’t use React 17.

Read the official React doc to learn more.

1. React Must Be in Scope

Let’s assume we are creating “helloWorld.jsx” like below, you can see there is a compilation error display as “’React’ must be in scope when using JSX react/react-in-jsx-scope.”

const element = <h1>Hello World!</h1>
export default element;


This happens due to “React” import necessary in JSX file.The React library must also always be in scope from JSX code. To overcome this error “import React from “react”;” must be added into the file as follows.

import React from 'react';

const element = <h1>Hello World!</h1>
export default element;

2. JSX value should be either an expression or a quoted JSX text 

You must use quotes to specify string literals as attributes as follows.

const Welcome = ({name}) => {

  return <h1>Welcome {name}</h1>
}

const element = <Welcome name="John" />

And also you must use curly braces to embed a javascript expression in an attribute.

const Welcome = ({name}) => {
 return <h1>Welcome {name}</h1> 
} 
const user = {
  name: 'John',
}

const element = <Welcome name={user.name} />

  

Otherwise, it will be given parsing error of “JSX value should be either an expression or a quoted JSX text” and compilation failed. 

3. Always start component names with an uppercase letter

React treats components starting with lowercase letters as DOM tags that represents an HTML.  To render a react component, the tag name must start with an uppercase letter. In this scenario, code will compile successfully but browser console will give warning as  “The tag <tagName> is unrecognized in this browser. If you meant to render a React component, start its name    with an uppercase letter.”

            Here ‘welcome’ must start with a capital letter.

Понравилась статья? Поделить с друзьями:
  • Immergas ошибка е10 как исправить
  • Immergas ошибка 10 мигает что делать
  • Immergas eolo star ошибка 01 что делать
  • Immergas eolo star коды ошибок
  • Immergas eolo mythos ошибка е11