2

I am Trying to use react-router-dom. When I export my component as

class RandomComponent { // component code}
export default RandomComponent;

and use this as a component in Route as following -

<Route path="/" exact component={RandomComponent} />

I get following warning in chrome console -

Warning: Failed prop type: Invalid prop component of type object supplied to Route, expected function

But When I export my component using

export class RandomComponent{ // component code}

same piece of code starts working, can someone explain me why this is happening? thanks in advance.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Abhishek Gangwar
  • 2,168
  • 18
  • 26

3 Answers3

0

You most probably tried to import your component with curly braces even though it is a default export.


DEFAULT EXPORT:

If you use export your component with default specified (default export), you need to import it without curly braces like this:

import RandomComponent from '../pathToComponent';

NAMED EXPORT:

But if you export your component without default specified (named export), you need to import it with curly braces like this:

import { RandomComponent } from '../pathToComponent';

Do note that you can only have one default export from a single file but as many named exports as you want from a single file.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
0

Warning: Failed prop type: Invalid prop component of type object supplied to Route, expected function

the passed prop is not a component but is an object. your class should extend React.Component

import React, {Component} from 'react'

class RandomComponent extends Component {/*your code*/}
Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123
0

This appears to be a bug in react-router prior to version 4.4.

At the time of writing the latest version is 5.2, and using that version fixed the issue for me:

npm install --save react-router@latest

If you're using react-router-dom you may also want to update that.

Be aware that if you are having this problem your react-router is at least 2 major versions out of date; and there may be significant work required to get your routes to work in the latest version. Update packages across major version boundaries cautiously.

thelastshadow
  • 3,406
  • 3
  • 33
  • 36