Search code examples
reactjsmaterial-uihookrouter

React Material UI Button component with hookrouter


I am trying to migrate a class component React app to functional components with hooks.

When using class components I use to pass a Link component to a Button component since I was using react-router-dom library.

But now I am trying to use Paratron/hookrouter library for routing but I get an error when passing an A component to the Button:

TypeError: props.href is undefined

My code now looks like this:

import React, { Fragment } from 'react';
import { Grid, Button } from '@material-ui/core';
import { A } from 'hookrouter';
import './styles.css';

const Home = props => {
  return (
    <Fragment>
      <Grid container spacing={24} className="landing">
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="primary" 
            size="large"
            component={A}
            to="/login"
          >Login</Button>
        </Grid>
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="secondary" 
            size="large"
            component={A}
            to="/contact"
          >Contact us</Button>
        </Grid>
      </Grid>
    </Fragment>
  );
}

export default Home;

I guess this A component does not contain an href property. Not sure how to proceed. Any comments will be appreciated.


Solution

  • You need to provide 'href' prop, not 'to' prop.

    <Fragment>
      <Grid container spacing={24} className="landing">
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="primary" 
            size="large"
            component={A}
            href="/login" //href
          >Login</Button>
        </Grid>
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="secondary" 
            size="large"
            component={A}
            href="/contact" //href
          >Contact us</Button>
        </Grid>
      </Grid>
    </Fragment>
    

    I also had to wrap A with class component, since A is probably function component, and they can't hold a ref (which is required by button component prop)

    You can refer to this working CodeSandbox demo