2

Im using material-ui and react-router-dom in my react (typescript) application

I have tried to use the following tip/help, so that when a user clicks a button (or whatever) he gets redirected to that route. Very basic stuff. When I click on the button, the url is updated in the url-window in my browser, but the correct component is not loaded. I had this working using bootstrap (and 'react-router-bootstrap's NavigationLink), but now Im stuck. Any tips how to get this working

(Im also using Mobx as state handler), Im also happy with any other router, if that makes my life simpler

https://material-ui.com/demos/buttons/ and How to make a Material UI react Button act as a react-router-dom Link?

Note that if I hit enter in the url-window I get routed correctly (to right component)

Cowborg
  • 1,490
  • 2
  • 19
  • 34

1 Answers1

1

I'm using this method to achieve a correct react-router-dom link for a Button component from material-ui.

Define a LinkComponent

import * as React from 'react';
import { Link } from 'react-router-dom';

export const LinkComponent = (props: any) => {
  return <Link {...props} />;
};

Then you can use it like this:

<Button
  variant={'outlined'}
  color={'primary'}
  component={LinkComponent}
  to={'/'}>
  HomePage
</Button>

If you don't want to create a dedicated component for this purpose, you can use it as a lambda function as a component prop for the <Button>.

Ammar Alakkad
  • 125
  • 1
  • 10
  • Hi Ammar! Thanks for your reply. I get 2 errors here, meybe Im misunderstand you. I created the LinkComponent, but I get the error "(TS) could not find name href", so I removed the "href ||"-part. On the – Cowborg Feb 26 '19 at 09:54
  • ...but I cant find a to-attribute here either https://material-ui.com/api/button/ – Cowborg Feb 26 '19 at 09:55
  • ... and even if I hardcode – Cowborg Feb 26 '19 at 10:03
  • @Cowborg Sorry for the href not found error, I updated the answer, please try it now. – Ammar Alakkad Feb 26 '19 at 12:11
  • tried that too, no difference. I think my problem is how I wire up the routing with mobx. I used react-router-bootstrap before, but since Im not using bootstrap now I need to look over that again ... I think – Cowborg Feb 26 '19 at 12:43