Receiving "Attempted import error:" in react app - reactjs

I am receiving the following error when trying to run my React app:
./src/components/App/App.js
Attempted import error: 'combineReducers'
is not exported from '../../store/reducers/'.
Here's how I'm exporting combineReducers:
import { combineReducers } from 'redux';
import userReducers from './userReducers';
import articleReducers from './articleReducers';
export default combineReducers({
userReducers,
articleReducers
});
and here's how I'm importing it in App.js:
import { combineReducers } from '../../store/reducers';
What's incorrect in how I'm exporting combineReducers?

import { combineReducers } from '../../store/reducers';
should be
import combineReducers from '../../store/reducers';
since it's a default export, and not a named export.
There's a good breakdown of the differences between the two here.

i had the same issue, but I just typed export on top and erased the default one on the bottom. Scroll down and check the comments.
import React, { Component } from "react";
export class Counter extends Component { // type this
export default Counter; // this is eliminated

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important.
if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me. 🙂

This is another option:
export default function Counter() {
}

Take into consideration that if you are using a named export you don't need curly brackets:
export const Component
->
import {ComponentName}
Only the default exported component be imported with curly brackets:
export default
->
import ComponentName

Maybe i'm late too but i had a similar problem with folders inside of component folder. i changed the folder's name with Capital letter. it worked for me.

If changing the import doesn't help maybe you just need to run yarn install or npm install (or whatever you're using) and restart your server. Worked for me.

Be sure to Capitalize the name of the constant variable you're exporting inside the component. When you Import the component elsewhere you should also check that its first letter is capitalized since this is one of the ways React uses to identify its components.
inside component:
import React from 'react';
export const Component = (props) => (...)
And then, when importing:
import {Component} from '../location/file'

Consider checking for any file renamings that git hasn't been instructed to track with git mv

Related

VSCode does not suggest auto import when re-exporting a default export in an index file

I'm working on a React app and came to this case.
Input:
The folder structure:
/ProductTypeSelection
index.tsx
ProductTypeSelectionView.tsx
ProductTypeSelectionView.tsx:
const ProductTypeSelectionView: React.FunctionComponent<ProductTypeSelectionViewProps> = () => {
return <div />;
};
export default ProductTypeSelectionView;
index.tsx:
export { default } from './ProductTypeSelectionView'
Desired output
Right now I could import that ProductTypeSelection component like this: import ProductTypeSelection from 'src/ProductTypeSelection' but the VSCode does not suggest auto-import for ProductTypeSelection (just ProductTypeSelectionView).
So my desired output would be able to use that import syntax and get the ProductTypeSelection import suggestion from VSCode at the same time. I wonder if this is achievable, thank you very much.
Tried
This will work as expected but wondering if I could re-write this in 1 line.
import ProductTypeSelection from "./ProductTypeSelectionView";
export default ProductTypeSelection;
You export a default, instead try:
export { default as ProductTypeSelectionView } from './ProductTypeSelectionView'

How to use import statement in react?

how to use import statement to import functions from one component to other component.
Below is how the import statement is:
import Tool from '../Common';
import { ToolContextProvider } from '../Common';
This complaint of duplicate lines. So I have tried something like below,
import { ToolContextProvider, Tool} from '../Common';
But this doesn't seem to be correct. How can write this in one line.
Could someone help me with this? Thanks.
basically there are two different type of export in javascript modules (also react included):
default export
named export
default export would be like :
// someFile.js
export default SomeComponent
named export would be like
// someFile.js
export SomeOtherComponent
importing them in other components for using them should be like:
// useCase.js
import SomeComponent from './someFile' // for default export
import { SomeOtherComponent } from './someFile' // for named export
import SomeComponent, { SomeOtherComponent } from './someFile' // for using both
You can import like this. Just combine both of them.
import Tool, { ToolContextProvider } from '../Common';

Element type is invalid: expected a string (for built-in components) or a class/function

import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/map/container/map';
import App from './App';
import './index.css';
import shell from './shared/utility/shell';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware, ConnectedRouter } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker';
import { Routes } from './config';
const history = createHistory();
const target = document.querySelector('#root')
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history)
];
if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
);
const store = createStore(
rootReducer,
initialState,
composedEnhancers
);
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<Routes />
</div>
</ConnectedRouter>
</Provider>,
target
)
registerServiceWorker();
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
I am trying to call an API from with the help of redux and display its data in a table. I am getting this error. Above is my index.js file.
1.
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
2.
React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
I have referred to many answers I am not able to recognize the error.
Problem is in the import statements. You have not used curly braces while importing some components like createHistory.
If a component uses a default export like:
export default X
Then you can simply import it like:
import X from './X';
But if you are using a named export like:
export const X=1;
Then you need to import it in curly braces like:
import {X} from './X';
So have a look at your imports. This will resolve your issue.
I ran into the same problem in my react application. It's definitely your import statements as stated above.
I changed:
import {x} from '/x.js' to import x from '/x.js'
and that got the job done
I've also run into this error when one of the nested components attempted to render a component that did not exist. Specifically, I attempted to use
<Button ... />
a react-native component in React, where I should have been using
<button ... />
It can also be caused from where the entry point is.
In my case, the App.js was calling index.js (where the developer console was identifying the error, and where my RenderDom call was).
However, App.js was referencing a component, and it was within that component that I had the error (a reference to yet another component that did not exist).
For me, I faced this issue when I forget to use react-redux's connect in my export.
So,
changing:
export default(mapStateToProps, mapDispatchToProps)(ContentTile);
To:
export default connect(mapStateToProps, mapDispatchToProps)(ContentTile);
solved the issue. Really silly mistake
There are several reasons why this error might occur.
It is definitely related directly to an issue with one of your imports. This could be:
A missing/miss-imported module from a npm package.
A component missing the export or an altogether empty component
attempting to be imported.
mixed up named/default export/import
Check you aren't importing your component name in braces like this:
import {SomeComponent} from '../path/to/SomeComponent'; // nope
I realised I had done that and so I changed it to this and it started working:
import SomeComponent from '../path/to/SomeComponent'; // yes
I believe the {} are for selecting from imports with multiple exports like the React components etc, and without you get what the export default is, but maybe someone can comment to confirm that.
To add to previous replies, you also get this error if one of the components within the component you are trying to import is empty / does not have a correct render method.
As was sayed above, this issue with import. In my case it's was a CSSTransitionGroup import. After npm update the package 'react-transition-group' no longer contains CSSTransitionGroup, but it's contains different exports, like CSSTransition and TransitionGroup. So i just replace line:
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
with
import TransitionGroup from 'react-transition-group/TransitionGroup';
In my case I solved it changing the components: They were written in functions declarations and I change them by classical Class declarations (class App extends React.Component instead of function App() )
I also had the similar problem while attempting to add routes into my application.
I then realised that i was importing { BrowserRouter, Route } from "react-router"; instead of correctly importing it from react-router-dom as below
import { BrowserRouter, Route } from "react-router-dom".
Thanks to the online community
Make sure you export the component. And if you are already exporting, then you might have missed the default.
export default function App(){
...
}
It's a special case, but Recharts threw this error for me when I attempted to put two charts inside one ResponsiveContainer. That is not supported.
You may also get this error if a sub-component of the component that the error references has not exported its function/class:
So the problem isn't in the referenced component but in a component that it is importing (which is not referenced in the error text).
Took me a while to find this bugger.
Sometimes, It could be as a result of importing from the wrong library, like in my experience, where I should have imported Input component from react native elements.
import { View, ActivityIndicator, Input } from 'react-native';
import { Input, Button } from 'react-native-elements';
In my case I resolved the problem by removing undefined component.
I imported that component from wrong module.
My problem is solved, the problem was instead of using
import { NavLink } from 'react-router-dom'
I used
import { NavLink } from 'react-dom'
I want to say this, coding includes paying attention to details.
I got this error just because import "FlatList" as "Flatlist" in react native expo project. And I spend one and a half hour to realize that :(
for me i was trying to route in app.js some component that have problem, so index.js will not render the / because of that in-proper import in app.js
so alwasy make sure components in app.js are working properly

What is use of curly braces in an ES6 import statement?

I can see there are two different ways to import:
import React from 'react'
import { render } from 'react-dom'
The second one has brackets. What is the difference between the two? And when should I add brackets?
Well, the difference between whether you should import your components within brackets or without it lies in the way you export it.
There are two types of exports
Default Export
Named Export
A component can have one default export and zero or more named exports.
If a component is a default export then you need to import it without brackets.
E.g.,
export default App;
The import it as
import App from './path/to/App';
A named export could be like
export const A = 25;
or
export {MyComponent};
Then you can import it as
import {A} from './path/to/A';
or
import {A as SomeName} from './path/to/A';
If your component has one default export and few named exports, you can even mix them together while importing
import App, {A as SomeName} from './path/to/file';
Similarly in case of react and react-dom, React and ReactDOM are default exports respectively whereas, for instance Component is a named export in react and render is a named export in react-dom. That's the reason you can either do
import ReactDOM from 'react-dom';
and then use
ReactDOM.render()
or use it like mentioned in your question.
First of all, a big thank you to all the other answers.
Here is a summary of all the above, in one answer.
Context with examples
import React from 'react'; // Importing without braces
import { render } from 'react-dom'; // Importing with braces
To be able to understand import, it's important to firstly understand export and its types.
Types of exports
There are mainly two types of exports, 'default' and 'named'. Whether to use braces or not, depends entirely on which type of exported variable is being imported.
So, the short answer is that variables exported as default, do not need braces, but named variables do need to be imported with braces.
Now, let's look at some practical examples of how to import and export both types.
Default: How to export and import
exporting
// Module1.js
export default App;
// Module2.js
export default myVariable;
// Module3.js
export default myFunction;
// Please note that there can only be one default export per module!
importing
import App from './Module1'
import AppRenamed from './Module1'
import myVariable from, './Module2'
import myFunction from './Module3'
// Please note that default modules can be renamed when importing
// ... and they will still work!
Named: How to export and import
exporting
export const A = 42
export const myA = 43
export const Something = 44
export { cube, foo, graph };
// Note how there can be several named exports per module
// exported in groups or individually
importing
import { A, myA } from './my-module.js';
import { Something as aRenamedVar } from './my-module.js';
import { cube } from './my-module.js';
import { foo, graph } from './my-module.js';
// Likewise, named exports can be imported in groups or individually
Other notes
let's revisit the very first example we saw above
import React from 'react'
import { render } from 'react-dom'
please note that although, React doesn't use braces, and render does, render is actually a part of react-dom.
therefore it is also possible to import the entire default react-dom
without braces and then use render
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render()
Consider primitives.js,
export default (a, b) => a + b;
export const sub = (a, b) => a - b;
export const sqr = a => a**2;
It can be imported like this,
import sum, { sub, sqr } from './primitives';
In this case, sum is called a "Default Export" and a module may contain a single "Default Export" only.
sub and sqr are called "Named Export" and a module may contain multiple named exports.
Curly braces are used to import single(specific) property, whereas the word without braces is import entire object form that file.
For example,
import React, { Component } from 'react';
Here the word React represents to import entire object from the file 'react'.
{Component} means we specify to import the particular property from the file.
There isn't any need to add brackets if you are exporting as default. You can have only default in the module.
Case 1:
export default function(num1, num2) {
return num1 + num2; }
Case 2:
function sum(num1, num2) {
return num1 + num2; }
export { sum as default };
Case 3:
function sum(num1, num2) {
return num1 + num2; }
export default sum;
You can import the default
import sum from "./test.js";
console.log(sum(1, 2));

When using ES6, how can an imported function be undefined in one file, and not in another?

I'm using babel / ES6 with webpack. I'm importing the same 'actions' file - which exports a bunch functions - in two different places. At one place it returns a module, the other undefined:
actions.js
export function test() { ... }
export function test2() { ... }
App.js
import actions from './actions'
class App extends React.Component { ... }
console.log(actions); //<-------- Object{test:function,test2:function)
export default connect((state) => { ... },actions)(App);
edit
the reason App.js worked was because it was actually using import * as actions as sugested below, I just retyped it wrong in the example
NestedComponent.js
import actions from './actions'
class NestedComponent extends OtherComponent { ... }
console.log(actions); //<-------- logs undefined
export default connect((state) => { ... },actions)(NestedComponent);
Is this related to the order in which webpack defines the modules/files?
I ran into a similar issue, caused by circular dependencies. Tried to import a constant in file 'A' from file 'B' which in turn tried to import from file 'A'.
This shouldn't work in either case because you are importing the wrong values. import foo from '...' imports the default export of the module, but you don't have a default export, you only have named exports.
What you should use is
import {test, test2} from './actions';
// or
import * as actions from './actions';
Another common case where this happens is if you're testing with Jest and auto-mocking behavior is enabled. Much grief, such gotcha.

Resources