'material-ui fab href does not add baseurl
In a React 16 application that uses material-ui. I have this FAB
<Fab color = "primary" aria-label = "Add" className = {classes.fab}
size = "small" href = "/technology/new">
<AddIcon/>
</Fab>
The application is configured to use "metro"
as base URL. so all routes and <NavLink>
append metro to the link. example "/dashboard"
becomes "metro/dashboard"
.
The problem is that <Fab>
does not append metro to the link. How Can I fix this?
Solution 1:[1]
Material UI does not connect with React Router (or other routing solutions) automatically.
Material UI does provide away to use its component styling while using external components for functionality, this would allow you to use React Router DOM's Link component as the base for Material UI's Fab component.
This is achieved by setting the component
prop of the Fab component (most of Material UI's components have this prop). The properties of the passed in component should be available for assignment directly on the Fab component (see Example).
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Switch, BrowserRouter, Route, Redirect, Link } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Hello from './Hello';
import './style.css';
import { Fab } from '@material-ui/core';
interface AppProps { }
interface AppState { }
const history = createBrowserHistory();
class App extends Component<AppProps, AppState> {
constructor(props) {
super(props);
this.state = {
name: 'React'
};
}
render() {
return (
<BrowserRouter
basename="test"
>
<Switch>
<Route path="/b" render={() => <div>B</div>} />
<Route path="/a" render={() => <div>A</div>} />
<Redirect path="*" to="/a" />
</Switch>
<Fab component={Link} to='/a'>A</Fab>
<Fab component={Link} to='/b'>B</Fab>
</BrowserRouter>
);
}
}
render(<App />, document.getElementById('root'));
Runnable Example: https://stackblitz.com/edit/react-ts-cngowu?file=index.tsx
Solution 2:[2]
You could handle click event of Fab
and programmatically navigate using history.push()
const handleClick = () => {
alert("already in here")
// history.push('/technology/new')
}
return (
<Fab color="primary" aria-label="add" onClick={handleClick}>
<AddIcon />
</Fab>
)
Demo codesandbox below
Solution 3:[3]
With MUI 5+ and react-router-dom 6+ you can wrap your FAB component with the react-router-dom Link component.
<Link to="/your-path">
<Fab color="primary" aria-label="add">
<AddIcon />
</Fab>
</Link>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jacob Smit |
Solution 2 | hgb123 |
Solution 3 | Thibaud Lacan |