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';
-
Вопрос заданболее двух лет назад
-
1326 просмотров
если не используются какие-нибудь хуки например useState
или useEffect
то можно и не подключать
Пригласить эксперта
Скорее всего у вас React подгружен на HTML странице (как на картинке ниже), в этом случае не нужно импортировать как модуль.
Другой способ подключения это установить библиотеку react через npm и импортировать его в коде.
import React from 'react';
Про это все написано в доках React, советую их смотреть, а не ролики, тем более там есть русский язык.
-
Показать ещё
Загружается…
04 июн. 2023, в 01:35
1500 руб./за проект
04 июн. 2023, в 01:25
40000 руб./за проект
03 июн. 2023, в 23:42
1500 руб./за проект
Минуточку внимания
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.
`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:
`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 .
In this article, we will summarize the common errors that often occur in the process of making a React project. We will analyze the cause of the error and the solutions to fix it.
Attempted imported error ‘#’ is not exported from
Surely you’ve encountered this error at least once in your life while using React. The error “Attempted to import error “#”not exported from” occurs when you try to import a name that does not exist in your file. An example of the error message being sent is as follows:
Failed to compile.
Attempted import error: 'Infor' is not exported from './infor' (imported as 'Infor').
For error handling, when working with default exports, avoid using curly braces around names.
You can find other solutions analyzed by experts in this article:
- Attempted import error ‘#’ is not exported from
Type ‘#’ is missing the following properties from type ‘##’
When declaring properties for components you often get the error “Type ‘#’ is missing the following properties from type ‘##’”.
The cause of the error is that you didn’t pass enough properties or didn’t pass any of the required properties in the component. The simplest error-handling solution is to double-check the component’s properties and make sure you’ve passed all required component properties.
The article below summarizes solutions for error handling that you can refer to:
- Type is missing the following properties from type
Undefined symbols for architecture x86_64
When you run the simulator for React Native application with Xcode on a computer running M1 or M2, in case the program is not compatible with your ecosystem, it results in the error Undefined symbols for architecture x86_64.
The solution that works for you is to upgrade your current React Native version, you can run the command and optionally the version you want:
npm install -g [email protected]
npx react-native upgrade
Or also disable the emulator for ARM64 architecture to remove them.
Learn more about the error and how to deal with it in this article:
- React Native build error: Undefined symbols for architecture x86_64
useLocation() may be used only in the context of a Router component
The error occurs when you don’t use useLocation inside the Router context in react-router.
The solution to this error is that you can wrap it inside a Router component:
import React from "react";
import { useLocation } from "react-router-dom";
const App = () => {
const location = useLocation();
return (
<div>
<button
onClick={() => {
console.log(location);
}}
>
Click Me
</button>
</div>
);
};
export default App;
In React, React-Router is considered the standard routing library to keep the application’s URL and interface in sync. To do this, the useLocation() hook is the method for React to do it. Learn more about errors and other interesting knowledge in the article below:
- useLocation() may be used only in the context of a Router component
React hook useeffect has a missing dependency
An error occurs when the use of the “useEffect” hook includes a variable or a function that is not included in the dependencies array. Simply put, when working with the useEffect hook, it will require returning an array of dependencies. For example:
const anArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
useEffect(() => {
console.log(anArray);
}, [anArray]);
The result of the anArray argument passed in the second argument is an array of dependencies.
In the article below, we have detailed instructions on error handling steps and specific examples, refer to it right here:
- react hook useeffect has a missing dependency error
A component is changing an uncontrolled input to be controlled
The error occurs when you have not passed the initial value and as such it is considered undefined. As a workaround you can either pass it an empty string or use the nullish association operator (??) to check the variable’s determinism. For example:
function App() {
const [name, setName] = useState(""); // <--- Initial with an empty string
const handleInput = (e) => {
setName(e.target.value);
};
We have compiled detailed instructions in the article below:
- a component is changing an uncontrolled input to be controlled
Module not found: can’t resolve ‘#’
The error occurs when you access the file with the incorrect path or you have not installed the third-party packages to support this feature. The fix is you can execute below commands in your file:
rm -rf node_modules
rm -f package-lock.json
npm install
Learn more and see detailed handling instructions in the article below:
- Module not found: can’t resolve ‘#’ error in react
Adjacent JSX elements must be wrapped in an enclosing tag
When you try to render more than one element in the program, this is what causes the above error. The workaround is to wrap all the elements in an element and get it as the root element or use Fragments. See detailed examples in the article below:
- Adjacent JSX elements must be wrapped in an enclosing tag
Property ‘value’ does not exist on type EventTarget
When working with the DOM in Typescript, you may encounter this error. For example:
function App() {
const handleOnclick = (event: Event) => {
console.log(event.target.value);
};
return (
<div>
<button onClick={handleOnclick} id="message">Click me!</button>
</div>
);
}
export default App;
The result returns an error message because you chose the wrong event type and the system failed to get the element’s value. Follow the ways to handle right in the article below:
- Property ‘value’ does not exist on type EventTarget
You Cannot Render A Router Inside Another Router
When working with React-router-dom, users will often encounter problems related to router settings. The above error is caused by using more than one <Router> component in the project and this is causing the conflict. The course of action is to adjust and reset the router. You can follow the specific steps in this article:
- You cannot render a Router inside another Router
Module not found: Can’t resolve ‘@emotion/react
When you enter the following command while its package is not installed:
import { css } from '@emotion/react';
The above error will occur because this feature is not yet supported. The simple solution is to install the @emotion/react package in your file so you can take it out anytime. Detailed instructions on how to install the package are in this article:
- module not found: can’t resolve @emotion/react
Module not found: Can’t resolve ‘@mui/material
When you don’t have any of these packages installed:
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
Then after entering them, the system will return an error message for you. The reason is simply because you do not have Material UI installed on your computer. The simple way to handle the error is to add the missing one. You can see the installation step-by-step instructions in the article below:
- Module not found: Can’t resolve ‘@mui/material’
useNavigate() may be used only in the context of a Router component
The error occurs because you use the useNavigate() hook outside the scope of the React component. To put it simply, the useNavigate() hook must be nested inside the Router. So a quick way to handle the error is that you need to incorporate all the components that use the useNavigate() hook into the React component in your project. Detailed steps are mentioned here:
- useNavigate() may be used only in the context of a Router component
useRoutes() may be used only in the context of Router component
This is also a similar case when you work with hooks useNavigate(), useLocation() … The reason is because these hooks need to be nested inside the Project’s Router. The concrete solution is to wrap them in a react component. Details of solutions are in this article:
- useRoutes() may be used only in the context of Router component
React refers to UMD global, but the current file is a module
The cause of this error is using an old version that causes when you import a React statement that contains jsx, react recognizes your file as a component. As a workaround you can use import React so that React will enqueue this file as a component, for example:
import React from "react"
const Component =()=>{
return( <>Hello LearnShareIT</>)
}
export default Component
In addition, you can refer to some other ways in this article:
- React refers to UMD global, but the current file is a module
Other
- sh: react-scripts: command not found
- error “ReactDOM.render is no longer supported in React 18. Use createRoot instead”
- Module not found: Can’t resolve ‘popper.js’
- Module not found: Can’t resolve ‘react/jsx-runtime’
- Property ‘value’ does not exist on type HTMLElement
- Too many re-renders. React limits the number of renders to prevent an infinite loop
- Export ‘usehistory’ was not found in react-router-dom
- Error [err_package_path_not_exported]: package subpath
- Can’t perform a React state update on an unmounted component in React-hooks
- Expected corresponding JSX closing tag error in React – How to fix it?
- This JSX tag’s ‘children’ prop expects single child of type ‘Element’, but multiple children were provided – How to fix this error?
- How To Fix Module not found: Can’t resolve ‘@date-io/date-fns’
- Module not found: Can’t resolve ‘react-bootstrap’ in React
- Property does not exist on type ‘JSX.IntrinsicElements’
- Cannot read property ‘pathname’ of undefined in React
- Module not found: Can’t resolve ‘styled-components’
- Module not found: Can’t resolve ‘react-dom’
- Module not found: Can’t resolve ‘rxjs’ in React
- Module not found: Can’t resolve ‘sass-loader’ in React
- Module not found: Can’t resolve ‘axios’ in React
- “Cannot find name” error in React Typescript
- React Hook ‘useState’ cannot be called in class component
- Module not found: Can’t resolve ‘jquery’ in React
- “Invalid DOM property `for` warning” in React
- Module not found: Can’t resolve @babel/runtime/helpers
- Functions are not valid as a React child error
- Module not found: Can’t resolve ‘moment’ error
- Parameter ‘event’ implicitly has ‘any’ type in React
- React.js: Property ‘children’ does not exist on type ‘#’
- useHref() may be used only in the context of a Router component
- create-react-app.ps1 cannot be loaded because running scripts is disabled on this system
- `value` prop on `input` should not be null in React
- Does not contain a default export Error in React.js
- TypeError: map() is not a function in React
- Property does not exist on type ‘never’ in React
- Module not found: Can’t resolve ‘babel-loader’
- You are running `create-react-app` 4.0.3, which is behind the latest release (5.0.0)
- Unexpected default export of anonymous function
- Only one default export allowed per module in React
- Binding element ‘#’ implicitly has an ‘any’ type in React
- Module not found: Can’t resolve ‘react-transition-group’
- No duplicate props allowed warning in React
- Module not found: Can’t resolve ‘reactstrap’
- Assign object to variable before exporting as module default
- Module not found: Can’t resolve ‘react-router-dom’
- Module not found: Can’t resolve ‘ts-loader’ error
- React Hook ‘useEffect’ is called in function that is neither a React function component nor a custom React Hook function
- Function components cannot have string refs in React
- Expected an assignment or function call and instead saw an expression
- Export ‘Switch’ (imported as ‘Switch’) was not found in ‘react-router-dom’
- JSX element type does not have any construct or call signatures
- react-scripts’ is not recognized as an internal or external command
- ‘#’ is not defined react/jsx-no-undef Error in React
Summary
In this article, we have summarized common React Error Messages and presented ways to deal with them. Always be careful to avoid unexpected errors that affect your working process. Follow our other articles to gain more necessary IT knowledge.
Hi guys, wellcome to LearnShareIt. I’m Tiffany and I’m also who responsible for the quality of this website’s content. I previously worked on software development projects for ten years as a developer. Hopefully, our project will bring a lot of value to the community.
Job: Programmer/Project management
Major: IT
Programming Languages: Python, C, HTML, MySQL, SQL Server, C#, C++, Javascript, CSS, Java, VB
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.
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.