How can i put the routerlink in reactjs button?
I tried these two below: the first one changes the color while the second one, i don't like it since it is reloading the page.
FIRST
<Link to="/settings">
<IconButton color="inherit">
<SettingsIcon />
</IconButton>
</Link>
SECOND
<IconButton color="inherit" href="/settings">
<SettingsIcon />
</IconButton>
To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.
React Router switches from server-side to client-side routing, so when you click on the Link component, the app checks the route and loads the requested component without reloading the full page in the browser.
Any answer here which suggests nesting a html button in a React Router Link component (or vice-versa) will render in a web browser, but it is not semantic, accessible, or valid html: This can lead to layout/styling issues as buttons are not typically placed inside links. Using an html <button> tag with React Router <Link> component.
You can change the route using a button with the following code: <button onClick= { () => props.history.push ("path")}> React Router provides some props to your components, including the push () function on history which works pretty much like the < Link to='path' > element.
Follow the steps given below to install Router in your React application: Step 1: cd into your project directory i.e geeks. After installing react-router-dom, add its components to your React application. Adding React Router Components: The main Components of React Router are:
To add the link in the menu, use the <NavLink /> component by react-router-dom. The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.
@BeHappy's solution is good, but you can implement this using composition. No need to use hook.
import React from 'react';
import { Link } from 'react-router-dom';
import { IconButton } from '@material-ui/core';
import SettingsIcon from '@material-ui/icons/Settings';
export default function Component() {
return (
<IconButton component={Link} to="/setting">
<SettingsIcon />
</IconButton>
);
}
import React from "react";
import { useHistory } from "react-router-dom";
export default function Component() {
const history = useHistory();
return (
<IconButton color="inherit" onClick={() => history.push("/setting")}>
<SettingsIcon />
</IconButton>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With