Nevolgograd
Nevolgograd

Reputation: 321

Uncaught TypeError: Cannot read property 'history' of undefined

I'm using react-router v4.1.1 and when i'm trying to use Link component - i get a warning:

Failed context type: The context `router` is marked as required in `Link`, 
but its value is `undefined`.

and also an error:

Uncaught TypeError: Cannot read property 'history' of undefined

Error is in the Link component on this string:

var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to);

Why router is undefined?

I'm importing BrowserRouter and Route in one of mine component which is responsible only for rendering selected page in the menu. And a Link importing in another component, which is actually a Menu component with unordered list.

I'll attach all my components if needed. Thank you for your help.

Upvotes: 2

Views: 1912

Answers (1)

Chandrakant Thakkar
Chandrakant Thakkar

Reputation: 978

if you want to use this

var href = this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to);

You need to register router with your component as following in your component put this code

 static contextTypes = { 
   router: React.PropTypes.object 
} 

Upvotes: 4

Related Questions