I have these buttons to which I would like to add link for redirect:
<Tooltip title="Open New Ticket">
<IconButton aria-label="filter list">
<AddTwoToneIcon />
</IconButton>
</Tooltip>
I added this:
<Tooltip title="Open New Ticket">
<Link to='open-ticket'>
<IconButton aria-label="filter list">
<AddTwoToneIcon />
</IconButton>
</Link>
</Tooltip>
But when I press the button I'm not redirected to a new page. This button for example is working fine:
<Link to='open-ticket'>
<Button
variant="contained"
color="primary"
size="small"
startIcon={<SaveIcon />}
>
Open Ticket
</Button>
</Link>
Do you know what is the proper way to implement this functionality?
CodePudding user response:
- Make sure you have installed
react-router-dom
.@material-ui/core/Link
will not work. - Import
BrowserRouter
fromreact-router-dom
and wrap your root component within.
import { BrowserRouter } from "react-router-dom"
import Root from "./views/Routes";
...
const App = props => {
return (
<BrowserRouter>
<Root />
</BrowserRouter>
);
}
- In your
Root
component, specify theRoute
s withpath
andrender
component and wrap them insideSwitch
component.Switch
enforces that only one of theRoute
children are matched. The URL is evaluated againstRoute
components insideSwitch
and the firstRoute
component whosepath
is a prefix-match of URL, is rendered. That is why you have to be careful of the order ofRoute
components insideSwitch
import { Fragment } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
import Main from "./Main";
import Home from "./Home";
import About from "./About";
import NotFound from "./404";
const Root = (props) => {
return (
<Fragment>
<Main />
<Switch>
<Route path="/about" render={(p) => <About {...p} />} />
<Route path="/404" render={(p) => <NotFound {...p} />} />
<Route path="/" render={(p) => <Home {...p} />} />
<Redirect to="/404" />
</Switch>
</Fragment>
);
};
export default Root;
- Use
Link
fromreact-router-dom
import { Link } from "react-router-dom";
import { Tooltip, IconButton, Grid } from "@material-ui/core";
import { HomeTwoTone, InfoTwoTone } from "@material-ui/icons";
const Main = (props) => {
return (
<Grid container spacing={2} justifyContent="center">
<Grid item>
<Tooltip title="Home Page">
<Link to="/">
<IconButton aria-label="filter list">
<HomeTwoTone />
</IconButton>
</Link>
</Tooltip>
</Grid>
<Grid item>
<Tooltip title="About Page">
<Link to="/about">
<IconButton aria-label="filter list">
<InfoTwoTone />
</IconButton>
</Link>
</Tooltip>
</Grid>
</Grid>
);
};
export default Main;
Here is a working demo
CodePudding user response:
Inside your button you can add:
onClick={event => window.location.href='/your-href'}