RLH
RLH

Reputation: 15698

In React, how do you properly programmatically navigate to a new route/page?

I've been trying to find a straight answer to this and even after searching StackOverflow, I can't find a correct answer for the current version of React.

In my case, I have the following scenario-- the user sets up their data, they post it to the server and within my Save() method, if the save operation is successful, I want to redirect them to the root home page.

Much of the documentation I've found mentions using this.props.history.push(...) to push the new route. However, something has changed with React 4.0.0+ and now history is undefined on the props page.

I am not necessarily interested in pushing the new route to the history object if that is a deprecated way of routing to another page. However, all of the more current examples I've found talk about setting up routes and links within the JSX. That's fine, but I've yet to find a way to programmatically redirect the page un certain code conditions.

Apologies if there is an answer out this already, but I haven't found a straight answer.

Upvotes: 1

Views: 274

Answers (2)

Tholle
Tholle

Reputation: 112777

The route props are only given to the components that are used for the component or render props of the Route components.

If you want to use the route props in any other component in your app, you need to pass the props manually or use the withRouter HOC.

import { withRouter } from "react-router-dom";

// ...

export default withRouter(MyComponent);

Upvotes: 1

XPowerDev
XPowerDev

Reputation: 164

You have to connect this component with router. To connect you have to use withRouter.

export default withStyles(commonModalStyle)(withRouter(connect(mapStateToProps, mapDispatchToProps)(NewOrUpdateModal)));

Please refer this

Upvotes: 0

Related Questions