How To Navigate On Path By Button Click In React Router V4?
I have this paths in react-router-dom: {/* app = home */} ;
...
classAppextendsReact.Component {
...
nextPath(path) {
this.props.history.push(path);
}
render() {
return (
<buttononClick={() => this.nextPath('/the/path') }>
change path
</button>
);
}
}
exportdefaultwithRouter(App);
Solution 2:
If you're using the button only for navigation, you can replace it with <Link />
and apply a button style.
<Linkto='/new/location/'>Click Me</Link>
Or you can use the <NavLink />
.
In case of using Material UI, you can use the following code:
import { Link } from'react-router-dom'importButtonfrom'@material-ui/core/Button';
<Buttoncomponent={Link}to="/new/location/">
Click Me
</Button>
(1): import {Link} from "react-router-dom";
(2): import {NavLink} from "react-router-dom";
Solution 3:
react-router-dom
exports a hook called useHistory
.
Just import it and use it in your component like this:
importReactfrom'react';
import { useHistory } from'react-router-dom';
exportdefault () => {
const history = useHistory();
return (
<buttononClick={() => history.push('/your/path')}>
Click me
</button>
);
};
I'm using:
- "react": "^16.13.1"
- "react-router-dom": "^5.2.0"
Check this post for more details: https://ultimatecourses.com/blog/programmatically-navigate-react-router
Post a Comment for "How To Navigate On Path By Button Click In React Router V4?"