React.createElement: type is invalid -- expected a string
Asked Answered
S

49

278

Trying to get react-router (v4.0.0) and react-hot-loader (3.0.0-beta.6) to play nicely, but getting the following error in the browser console:

Warning: 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.

index.js:

import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';

const renderApp = (appRoutes) => {
    ReactDom.render(appRoutes, document.getElementById('root'));
};

renderApp( routes() );

routes.js:

import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';

const routes = () => (

    <AppContainer>
        <Provider store={store}>
            <Router history={browserHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={Products} />
                    <Route path="/basket" component={Basket} />
                </Route>
            </Router>
        </Provider>
    </AppContainer>

);

export default routes;
Staw answered 15/3, 2017 at 14:57 Comment(2)
If you use react-router-config make sure you use the component property instead of render, because the package doesn't support the later. See more on GitHub.Jaquith
Check if you have created the component you are trying to import or it actually exists in the project directory.Festal
P
283

Most of the time this is due to an incorrect export/import.

Common error:

// File: LeComponent.js
export class LeComponent extends React.Component { ... }

// File: App.js
import LeComponent from './LeComponent';

Possible option:

// File: LeComponent.js 
export default class LeComponent extends React.Component { ... }

// File: App.js
import LeComponent from './LeComponent';

There are a few ways it could be wrong, but that error is because of an import/export mismatch 60% of the time, everytime.

Edit

Typically you should get a stacktrace that indicates an approximate location of where the failure occurs. This generally follows straight after the message you have in your original question.

If it doesn't show, it might be worth investigating why (it might be a build setting that you're missing). Regardless, if it doesn't show, the only course of action is narrowing down where the export/import is failing.

Sadly, the only way to do it, without a stacktrace is to manually remove each module/submodule until you don't get the error anymore, then work your way back up the stack.

Edit 2

Via comments, it was indeed an import issue, specifically importing a module that didn't exist

Pryor answered 15/3, 2017 at 15:29 Comment(15)
Have looked at the trace which points to line 12 of routes.js. That line is <IndexRoute component={Products} />Staw
Are you sure index route is actually part of RR4? (I'm pretty sure it isn't)Pryor
That was the issue - thanks! I have reverted back to v3.0.0Staw
Great, good stuff. Feel free to mark it as the accepted answer as it will help future readers know how to approach similar issuesPryor
Hey JoeTidee -- if you want to stay with RR4, follow this guide. I'm in the same boat at the moment... github.com/ReactTraining/react-router/blob/master/packages/…Donelladonelle
Had the issue with import { Select } from 'react-select'; and changed it to import Select from 'react-select';Firebreak
"warning" is not same as error. I get this warning and the import file path is correct.Peres
@PriyaRanjanSingh It's impossible to tell from just a little comment. Can you post a new question with details?Pryor
@AnkitJindal shouldn't matter if its a HOC or not. Can you raise a new question or provide more info?Pryor
In my case it was import { FooBar } instead of import { Foobar } that was the issue.Purulence
See the "Edit 2" by Chris above. Just ensure that your importing module is NOT empty. This was my issue and after adding some content it has been solved)Litton
also for me a import issue but it didn't seem that way at first, was pointing somewhere else, eventually trailed to silly import errorPhagocyte
It's also possible that react-redux is mocked or overwritten. If you have __mocks__/react-redux.ts file, removing it might help.Industrialize
Import issue for me (used brackets on an import of a "default export"). So glad it was that simple... thanks for the help <3Hekking
I faced same error and fixed it by changing import { ThumbUpAltIcon } from "@material-ui/icons/ThumbUpAlt"; TO import ThumbUpAltIcon from "@material-ui/icons/ThumbUpAlt";Tenno
F
65

I was getting this error as well.

I was using:

import BrowserRouter from 'react-router-dom';

Fix was doing this, instead:

import { BrowserRouter } from 'react-router-dom';

Felipafelipe answered 4/1, 2018 at 17:56 Comment(1)
or vice versa - I was using import {AppLoading} from 'expo-app-loading' instead of import AppLoading from 'expo-app-loading'Pyelography
A
18

Try this

npm i react-router-dom@next

in your App.js

import { BrowserRouter as Router, Route } from 'react-router-dom'

const Home = () => <h1>Home</h1>

const App = () =>(
  <Router>
    <Route path="/" component={Home} />
  </Router>
)

export default App;
Aggressive answered 9/5, 2017 at 11:25 Comment(1)
how will you send/receive props to home component then?Louvenialouver
G
15

Array of components

A common way to get this error is using an array of components, with a positional index used to select the component to render from the array. I saw a code like this many times:

const checkoutSteps = [Address, Shipment, Payment]

export const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

This is not necessary bad code, but if you call it with a wrong index (eg -1, or 3 in this case), the ToRender component will be undefined, throwing the React.createElement: type is invalid... error:

<Checkout step={0} /> // <Address />
<Checkout step={1} /> // <Shipment />
<Checkout step={2} /> // <Payment />
<Checkout step={3} /> // undefined
<Checkout step={-1} /> // undefined

A rational solution

You should protect yourself and your collegues from this hard-to-debug code using a more explicit approach, avoiding magic numbers and using PropTypes:

const checkoutSteps = {
  address: Address,
  shipment Shipment,
  payment: Payment
}

const propTypes = {
  step: PropTypes.oneOf(['address', 'shipment', 'payment']),
}

/* TIP: easier to maintain
const propTypes = {
  step: PropTypes.oneOf(Object.keys(checkoutSteps)),
}
*/

const Checkout = ({step}) => {

  const ToRender = checkoutSteps[step]

  return (
    <ToRender />
  )
}

Checkout.propTypes = propTypes

export default Checkout

And your code will look like this:

// OK
<Checkout step="address" /> // <Address />
<Checkout step="shipment" /> // <Shipment />
<Checkout step="payment" /> // <Payment />

// Errors
<Checkout step="wrongstep" /> // explicit error "step must be one of..."
<Checkout step={3} /> // explicit error (same as above)
<Checkout step={myWrongVar} /> // explicit error (same as above)

Benefits of this approach

  • code is more explicit, you can clearly see what you want to render
  • you don't need to remember the numbers and their hidden meaning (1 is for Address, 2 is for...)
  • errors are explicit too
  • no headache for your peers :)
Garland answered 8/6, 2020 at 9:5 Comment(1)
Really appreciate that you provide another example of how this error can happen outside of named vs default export. ThanksTranship
K
11

You need to be aware of named export and default export. See When should I use curly braces for ES6 import?

In my case, I fixed it by changing from

import Provider from 'react-redux'

to

import { Provider } from 'react-redux'
Kohinoor answered 13/3, 2018 at 15:21 Comment(1)
i've narrowed my issue down to this Provider. however, i'm already using the { Provider } notation.Pesthouse
L
6

Circular dependency is also one of the reasons for this. [in general]

Londrina answered 25/10, 2019 at 13:9 Comment(1)
Yup, that was my case too.Mural
A
5

I had this problem when I added a css file to the same folder as the component file.

My import statement was:

import MyComponent from '../MyComponent'

which was fine when there was only a single file, MyComponent.jsx. (I saw this format in an example and gave it a try, then forgot I'd done it)

When I added MyComponent.scss to the same folder, the import then failed. Maybe JavaScript loaded the .scss file instead, and so there was no error.

My conclusion: always specify the file extension even if there is only one file, in case you add another one later.

Anatomist answered 27/2, 2018 at 18:17 Comment(1)
Hi all, noob here. I think it was certainly a naming convention that was the issue for me, to me the logic above sounds right.Francescafrancesco
F
4

I think the most important thing to realize when troubleshooting this bug is that it manifests when you attempt to instantiate a component that doesn't exist. This component doesn't have to be imported. In my case I was passing components as properties. I forgot to update one of the calls to properly pass the component after some refactoring. Unfortunately, since JS isn't statically typed my bug wasn't caught, and it took some time to figure out what was happening.

To troubleshoot this bug inspect the component before you render it, to make sure that it's the type of component you expect.

Fedora answered 21/9, 2019 at 14:54 Comment(1)
"it manifests when you attempt to instantiate a component that doesn't exist" -- this is what happened to me. The component was imported/exported correctly but I was passing it as a prop through an authorization route in react-router and forgot to change the render={props => <Component {...props} />} to component={Component}.Tupungato
S
4

In my case, VS Code let me down.

Here is the hierarchy of my components:

<HomeScreen> =>  <ProductItemComponent> =>  <BadgeProductComponent>

I had the wrong import of the ProductItemComponent. The fact is that this component used to be in the shared folder, but then it was moved to the home folder. But when I moved the file to another folder, the import did not update and remained the same:

../shared/components

At the same time, the component worked fine and VS Code did not highlight the error. But when I added a new BadgeProductComponent to the ProductItemComponent, I had a Render Error and thought that the problem was in the new BadgeProductComponent, because when this component was removed, everything worked!

And even more than that, if I went through a hotkey to the ProductItemComponent which had the ../shared/components address, then VS Code redirected me to the Home folder with the address ../home/components.

In general, check the correctness of all imports at all component levels.

Spearhead answered 3/9, 2021 at 12:38 Comment(0)
B
3

For future googlers:

My solution to this problem was to upgrade react and react-dom to their latest versions on NPM. Apparently I was importing a Component that was using the new fragment syntax and it was broken in my older version of React.

Bug answered 4/3, 2018 at 9:28 Comment(0)
C
3

This issue has occurred to me when I had a bad reference in my render/return statement. (point to a non existing class). Also check your return statement code for bad references.

Cartography answered 5/5, 2019 at 12:29 Comment(0)
T
3

Most of the time this indicates an import/export error. But be careful to not only make sure the referenced file in the stack trace is well exported itself, but also that this file is importing other components correctly. In my case the error was like this:

import React from 'react';

// Note the .css at the end, this is the cause of the error!
import SeeminglyUnimportantComponent from './SeeminglyUnimportantComponent.css';

const component = (props) => (            
  <div>
    <SeeminglyUnimportantComponent />
    {/* ... component code here */}
  </div>    
);

export default component;
Trochilus answered 28/6, 2019 at 23:5 Comment(1)
Thank you for this comment! I have this issue since updating some packages, and I've been scrolling through all of these comments and none of them are in issue in this code. But this was it- the problem file imports something else that is causing the error!Biggerstaff
A
3

I was missing a React Fragment:


function Bar({ children }) {

  return (
    <div>
     {children}
    </div>
  );
}

function Foo() {
  return (
    <Bar>
      <Baz/>
      <Qux/>
    </Bar>
  );
}

The code above throws the error above. But this fixes it:

<Bar>
  <>
    <Baz/>
    <Qux/>
  </>
</Bar>
Anet answered 12/11, 2019 at 12:59 Comment(2)
Happened to me when I added ReactCollapsingTable (yarn add react-collapsing-table). I managed to alternate between this warning (that resulted in a hydration error) and a 'window is not defined' that was detected inside the compiled react-collapsing-table module... Even wrapping with <div>...</div> doesn't help anymoreEfik
Eventually I re-transpiled the whole project from start (instead of hot-reload) and the problem recurred. Found the solution here: https://mcmap.net/q/110314/-react-createelement-type-is-invalid-expected-a-string-for-built-in-components-or-a-class-function-for-composite-components-but-got-object (instead of import module from 'module-name', use require(module-name).default)Efik
N
3

It means your import/export is incorrect.

  • Check newly added import/exports.
  • In my case I was using curly brackets unnecessary. Issue got resolved automatically when I removed these curly brackets.
import { OverlayTrigger } from 'react-bootstrap/OverlayTrigger';
Naranjo answered 12/11, 2020 at 10:47 Comment(0)
A
3

I was getting this error as well.

I was using:

import ReactDOM from 'react-dom';

Fix was doing this, instead:

import {ReactDOM} from 'react-dom';

Advocaat answered 16/2, 2021 at 4:51 Comment(5)
dude that does not work, its not even worth a thumbs downPolymerization
bro you are a genius, exactly my problem.Exorcism
In my case, it was another way around and resolved, anyway thanks.Catharina
in my case it was other way around so i was importing like this import { SidebarOption } from '../components/sidebarOption' and it was throwing error but when i removed the { } brackets. puff error goneDelafuente
export 'ReactDOM' (imported as 'ReactDOM') was not found in 'react-dom'Devotee
E
2

It's quite simple, really. I got this issue when I started coding React, and the problem is almost always because the import:

import React, { memo } from 'react';

You can use destructuring this because react lib has a property as memo, but you can not destructuring something like this

import { user } from 'assets/images/icons/Profile.svg';

because it's not a object.

Hope it helps!

Endicott answered 10/3, 2020 at 7:57 Comment(0)
B
2

My case was not an import issue like many of the answers above say. In mine we were using a wrapper component to do some translation logic and I was passing the child component in incorrectly like so:

const WrappedComponent = I18nWrapper(<ChildForm {...additionalProps} />);

When I should have been passing it in as a function:

const WrappedComponent = I18nWrapper(() => <ChildForm {...additionalProps} />);
Blastocyst answered 16/8, 2021 at 13:59 Comment(0)
S
2

For me, I had two files with the same name but different extensions (.js and .tsx). Thus in my import I had to specify the extension.

Shoreward answered 27/8, 2021 at 16:20 Comment(0)
S
1

What missing for me was I was using

import { Router, Route, browserHistory, IndexRoute } from 'react-router';

instead or correct answer should be :

import { BrowserRouter as Router, Route } from 'react-router-dom';

Ofcourse you need to add npm package react-router-dom:

npm install react-router-dom@next --save
Subheading answered 1/8, 2017 at 11:21 Comment(0)
V
1

If you have this error when testing a component, make sure that every child component render correctly when run alone, if one of your child component depend on external resources to render, try to mock it with jest or any other mocking lib:

Exemple:

jest.mock('pathToChildComponent', () => 'mock-child-component')
Valvulitis answered 11/6, 2019 at 14:13 Comment(0)
R
1

In my case, the error occurred when trying to use ContextApi. I have mistakenly used:

const MyContext = () => createContext()

But it should have been defined as:

const MyContext = createContext()

I am posting it here so that future visitors who get stuck on such a silly mistake will get it helpful to avoid hours of headache, coz this is not caused by incorrect import/export.

Ranice answered 12/7, 2019 at 8:3 Comment(0)
U
1

In my case I forgot to import and export my (new) elements called by the render in the index.js file.

Unshaped answered 20/1, 2020 at 11:44 Comment(0)
H
1

React.Fragment

fixed the issue for me

Error Code:

 return (
            <section className={classes.itemForm}>
             <Card>
             </Card> 
            </section>
      );

Fix

 return (
      <React.Fragment>
        <section className={classes.itemForm}>
         <Card>
         </Card> 
        </section>
      </React.Fragment>
  );
Hjerpe answered 8/5, 2020 at 6:29 Comment(0)
D
1
xxxxx.prototype = {
  dxxxx: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
};

You must add // eslint-disable-line react/forbid-prop-types, then it work!

Drome answered 2/11, 2020 at 4:24 Comment(0)
U
1

The application that I was working on, stored the name of react components as a widget configuration in the browser storage. Some of these components got deleted and the app was still trying to render them. By clearing the browser cache, I was able to resolve my issue.

Underthrust answered 26/2, 2021 at 19:29 Comment(0)
V
1

I have had this problem already. My workaround is:

At file config routes:

const routes = [
    { path: '/', title: '', component: Home },
    { path: '*', title: '', component: NotFound }
]

to:

const routes = [
    { path: '/', title: '', component: <Home /> },
    { path: '*', title: '', component: <NotFound /> }
]
Vondavonni answered 12/3, 2022 at 18:2 Comment(0)
H
1

For me this happened while I have tried to import a named import as default import, SO I got this error

import ProductCard from '../../../components/ProductCard' // that what caused the issue
Error: 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, or you might have mixed up default and named imports.

Check the render method of `TopVente`.

So I had to fix it by name import

import { ProductCard } from '../../../components/ProductCard'
Hargreaves answered 13/4, 2022 at 19:6 Comment(0)
S
1

In my case, while using Jest, I mocked some modules, and it causes the error because the mocked module doesn't include some component that is used in other areas.

So please check if you have some mocking function within your test component.

Sasha answered 22/6, 2022 at 4:22 Comment(0)
C
1

You might be returning object from some specific file instead just return the statement

WRONG:

import React from 'react'
const About = () => {   return ( <div>About</div>   ) }
export default About

CORRECT:

import React from 'react'
const About = () => {   return 
<div>About</div>} 
export default About
Consolute answered 11/8, 2022 at 14:8 Comment(0)
R
0

In my case, the order in which you create the component and render, mattered. I was rendering the component before creating it. The best way is to create the child component and then the parent components and then render the parent component. Changing the order fixed the issue for me.

Rodeo answered 15/6, 2018 at 14:59 Comment(0)
M
0

In my case I just had to upgrade from react-router-redux to react-router-redux@next. I'm assuming it must have been some sort of compatibility issue.

Militant answered 29/6, 2018 at 3:46 Comment(0)
C
0

I was getting this error and none of the responses was my case, it might help someone googling:

I was defining a Proptype wrong:

ids: PropTypes.array(PropTypes.string)

It should be:

ids: PropTypes.arrayOf(PropTypes.string)

VSCode and the compile error didnt give me a correct hint.

Cultivable answered 8/5, 2019 at 16:6 Comment(0)
O
0

This is an error that is some how had to debug. As it has been said many times, improper import/export can cause this error but surprisingly i got this error from a small bug in my react-router-dom authentication setup below is my case:

WRONG SETUP:

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
        {...rest}
        render={(props) => (token ? <Component {...props} /> : <Redirect to={{ pathname: "/login" }} />)}
    />
);

CORRECT SETUP:

const PrivateRoute = ({ component: Component, token, ...rest }) => (
    <Route
        {...rest}
        render={(props) => (token ? <Component {...props} /> : <Redirect to={{ pathname: "/login" }} />)}
    />
);

The only difference was I was deconstructing the token in the PrivateRoute component. By the way the token is gotten from localstorage like this const token = localStorage.getItem("authUser"); so if it is not there I know the user is not authenticated. This can also cause that error.

Olio answered 7/3, 2020 at 10:51 Comment(0)
S
0

This is not necessary a direct issue related to import/export. In my case, I was rendering a child element inside a parent element and the child element has jsx element / tag which is used but not imported. I imported it and I used it then it fixed the issue. So the problem was in jsx elements which are inside the child element NOT the export of child element itself.

Susannahsusanne answered 25/5, 2020 at 4:57 Comment(0)
P
0

I got the exactly same error, Do this instead:

npm install react-router@next 
react-router-dom@next
npm install --save history
Phreno answered 12/11, 2020 at 6:51 Comment(1)
And don't forget to restart your webpack watchingPhreno
H
0

In my case, I have added the same custom component as a props instead of actual props

   import AddAddress from '../../components/Manager/AddAddress';
    
    class Add extends React.PureComponent {
      render() {
        const {
          history,
          addressFormData,
          formErrors,
          addressChange,
          addAddress,
          isDefault,
          defaultChange
        } = this.props;
    

Error:

    return (
        <AddAddress
          addressFormData={addressFormData}
          formErrors={formErrors}
          addressChange={addressChange}
          addAddress={AddAddress} // here i have used the Component name as probs in same component itself instead of prob
          isDefault={isDefault}
          defaultChange={defaultChange}
        />
      </SubPage>

Solution:

return (
    <AddAddress
      addressFormData={addressFormData}
      formErrors={formErrors}
      addressChange={addressChange}
      addAddress={addAddress} // removed the component name and give prob name
      isDefault={isDefault}
      defaultChange={defaultChange}
    />
  </SubPage>
Hardspun answered 21/2, 2021 at 14:36 Comment(1)
What is prob? you mean prop?Harelda
E
0

So I had this issue, and I was able to fix it in a strange way. I thought I'd throw this out in case anyone else encountered it and was getting desperate.

I had a conditionally rendering react element, which rendered only when an object in state was greater than zero. Within the rendering function - when the ternary operator proved true, I received the error that this post is about. I was using a <React.Fragment> in my render function - which is the way I usually group children instead of the newer way with the newer short syntax (<> and </>).

However, when I changed the <React.Fragment> to the short syntax - the react element rendered correctly and the error stopped appearing. I took a look at Facebooks React-Fragment documentation, and I don't see any reason on there to believe there is a dramatic difference between the two that would cause this. Regardless, below are two simplified snippets of code for your review. The first one demonstrates the code that was yielding the error, and the second one demonstrates the code that fixed the issue. At the bottom is the render function of the component itself.

Hope someone finds this helpful.

Code Sample 1 - Error Conditionally Rendered React Element


  renderTimeFields = () => {
    return (
      <React.Fragment>
        <div className="align-left">
                <div className="input-row">
                  <label>Date: </label>
                  <input type="date" className="date" name="date" min={new Date().toISOString().split('T')[0]} required/>
                </div>
              </div>
              <div className="align-left sendOn-row">
                <div className="input-row">
                  <label>Time: </label>
                  <input type="time" className="time" name="time" required/>
                </div>
              </div>
      </React.Fragment>
    );
  }

Code Sample 2 - No Error Conditionally Rendered React Element


  renderTimeFields = () => {
    return (
      <>
        <div className="align-left">
                <div className="input-row">
                  <label>Date: </label>
                  <input type="date" className="date" name="date" min={new Date().toISOString().split('T')[0]} required/>
                </div>
              </div>
              <div className="align-left sendOn-row">
                <div className="input-row">
                  <label>Time: </label>
                  <input type="time" className="time" name="time" required/>
                </div>
              </div>
      </>
    );
  }

Render Function Within Component

render() {
<form>
...
{emailsInActiveScript > 1 ? this.renderTimeFields() : null}
</form>
etc...
}
Ezarra answered 10/7, 2021 at 2:43 Comment(0)
C
0

For me removing Switch solved the issue

import React from "react";
import "./styles.css";
import { Route, BrowserRouter, Routes } from "react-router-dom";
import LoginPage from "./pages/LoginPage";
import HomePage from "./pages/HomePage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route exact path="/" element={<HomePage />} />
        <Route path="/login" element={<LoginPage />} />
      </Routes>
    </BrowserRouter>
  );
}
Creature answered 18/1, 2022 at 10:53 Comment(0)
N
0

This issue happened when I was passing nothingundefined as a value to the child component I created. I did this <MyComponent src="" /> which caused the error. Then changed it to <MyComponent src=" " /> because I really wanted to pass in nothing...and it was resolved.

Nomarch answered 18/3, 2022 at 15:50 Comment(0)
A
0

In my case, I imported Avatar as like import { Avatar } from 'react-native-paper'; and while rendering I wrapped Avatar element in TouchableOpacity which caused the above problem. After removing TouchableOpacity, all good. <Avatar.Image source={{ uri: '...', }} size={80} />

Alviani answered 25/4, 2022 at 9:0 Comment(0)
W
0

In my case I have Text component inside my components and when I import that Text like this without curly braces that was cause of error

import Text from '..';  <-wrong

To fix this error I import Text inside curly braces like this

import {Text} from '..';  <-right
Waldenburg answered 25/7, 2022 at 6:44 Comment(0)
P
0

For me, this came from me doing something a bit weird with classes which have functional component properties, and if I referenced a component directly with <this.SomeComponent /> everything worked fine on a local create react app dev server, but failed when deployed to production!

import { FC } from 'react';

export class MyComponents {
  
  public ComponentOne: FC<{ name: string }> = ({ name }) => {
    return <h1>Hello {name}</h1>;
  };

  public ComponentTwo: FC<{ name: string }> = ({ name }) => {
    return <this.ComponentOne name={name} />; // <- using this. was the issue
  };

}

I was able to make a slight change to fix it:

import { FC } from 'react';

export class MyComponents {
  
  public ComponentOne: FC<{ name: string }> = ({ name }) => {
    return <h1>Hello {name}</h1>;
  };

  public ComponentTwo: FC<{ name: string }> = ({ name }) => {
    const ComponentOne = this.ComponentOne;
    return <ComponentOne name={name} />; // works!
  };

}
Putty answered 29/3, 2023 at 9:27 Comment(0)
P
0

I'll just add my two cents here as I've encountered a similar issue but in a different scenario - in a Jest test suite.

If you already had e.g. imported MemoryRouter from react-router-dom and then added a hook to mock, don't forget to keep other non-mocked things from the module to work as before. Use jest.requireActual.

import { MemoryRouter, useLocation } from 'react-router-dom';

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useLocation: jest.fn(),
}));

Otherwise, MemoryRouter will get undefined and you'll end up with the same error as the author had.

Participate answered 13/6, 2023 at 9:40 Comment(0)
B
0

In my case I forgot to save the file of a module from which a component imported some components 😅

Bertilla answered 14/3 at 13:11 Comment(0)
O
-1

In simply words, somehow the following is happening:

render() {
    return (
        <MyComponent /> // MyComponent is undefined.
    );
}

It may not necessarily be related with some incorrect import or export:

render() {
    // MyComponent may be undefined here, for example.
    const MyComponent = this.wizards[this.currentStep];

    return (
        <MyComponent />
    );
}
Ovenbird answered 18/12, 2018 at 16:53 Comment(0)
T
-1

I just spent 30 minutes trying to solve this BASIC basic issue.

My problem was I was importing react native elements

eg import React, { Text, Image, Component } from 'react';

And trying to use them, which caused me to receive this error.

Once I switch from <Text> to <p> and <Image> to <img> everything worked as expected.

Traumatism answered 31/3, 2019 at 22:13 Comment(0)
T
-1
// @flow

import React from 'react';
import { styleLocal } from './styles';
import {
  View,
  Text,
  TextInput,
  Image,
} from 'react-native';
import { TouchableOpacity } from 'react-native-gesture-handler';

export default React.forwardRef((props, ref) => {
const { onSeachClick, onChangeTextSearch , ...otherProps } = props;

  return (
        <View style={styleLocal.sectionStyle}>
        <TouchableOpacity onPress={onSeachClick}>
            <Image                              
                    source={require('../../assets/imgs/search.png')}
                    style={styleLocal.imageStyle} />
                </TouchableOpacity>
            <TextInput
                style={{ flex: 1, fontSize: 18 }}
                placeholder="Search Here"
                underlineColorAndroid="transparent"
                onChangeText={(text) => { onChangeTextSearch(text) }}
            />
        </View>
  );
});
 import IGPSSearch from '../../components/IGPSSearch';
<Search onSeachClick={onSeachClick} onChangeTextSearch= {onChangeTextSearch}> </Search>
Teide answered 3/2, 2021 at 20:5 Comment(0)
H
-1

I have a similar issue. It was happen because I was importing in a parent component a child component that was deleted and in effect not exist. I was review each import of parent component, in this case the parent compent is ListaNegra.js

enter image description here

Hoitytoity answered 25/9, 2021 at 5:5 Comment(0)
D
-4

EDIT

You are complexifying the process. Just do this :

index.js:

import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';

ReactDom.render(<routes />, document.getElementById('root'));

routes.js:

import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';

const routes =
    <AppContainer>
        <Provider store={store}>
            <Router history={browserHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={Products} />
                    <Route path="/basket" component={Basket} />
                </Route>
            </Router>
        </Provider>
    </AppContainer>;

export default routes;
Downward answered 15/3, 2017 at 15:14 Comment(1)
Are you sure the problem comes from here ? And not from the pages themselves ?Downward

© 2022 - 2024 — McMap. All rights reserved.