Wondering how to go back to a previous route in a react web app using hashRouter instead of browserRouter in react-router v4?
I've found this question which doesn't seem to work even though it says no browser mixin needed (plus I think its talking about an older react-router version) however, every other solution I've seen depends on browserHistory.
Is it possible with hashHistory?
this.props.history.goBack()
Taken from the comments on this question
It is a function call.
Well in my case i did like that :
import withRouter from "react-router-dom/es/withRouter";
import React from "react";
class Component extends React.Component {
goBack() {
this.props.history.go(-1);
}
...
}
const WrappedComponent = withRouter(Component)
export default WrappedComponent;
withRouter give us access to history in props of component, but i'm not sure is this way is correct
Related
I am working on a web app that is consisted of few pages and have configured routes with react-route-dom. On the pages, I have some shared components and I want them to be styled differently on other pages except the Home page.
How do I get this done? Any help?
Thanks
Check if pathname is path of home or else not you can use useLocation to get the pathname and add conditional styling or classes.
useLocation v5
useLocation v6
import React from 'react';
import {useLocation} from 'react-router-dom';
export const Common_Component=()=>{
const location=useLocation()
const pathname=location.pathname
return(
<div>
<div classes={pathname=="home"?"home_class":"other_class"}>
...
</div>
</div>
)
}
Or
You can pass boolean props to the component to let component know it should use home bases classes or other classes.
PS.
you will still need to do conditional check if props is true or false
useMatch you can use useMatch to match the current url with regex.
While it is always good to share code, I would recommend creating a new component for the homepage. Otherwise you are coupling your components. What happens if you want to add another specialisation for the whatever-component? You add another case! Your components grow and wire up more and more until you have one big pot of spaghetti. Hence, it makes sense in many situations to just create a new component for a new use-case.
I have a logout function in app (same level as router) that's passed down to various pages so the user can logout from anywhere. How can I add a redirect when the function is called?
I tried using this.props.history.push("/"); but get error Cannot read property 'push' of undefined
To answer to your question we need to know which router you are using and which version.
If you are using react-router you can have a look at https://tylermcginnis.com/react-router-programmatically-navigate/
Use the (withRouter) high-order component
Sample
import React from "react";
import { withRouter } from "react-router-dom";
class App extends React.Component {
...
handleSubmit=()=>{
this.props.history.push("/path");
}
...
}
export default withRouter(App);
Live demo with sample code
I am new using react router v4. I have a link that runs a function in the onClick event and then redirects to a specific route.
This is the link:
<Link className={''}
to={'/test'}
onClick={this.testFunction}>To test</Link>
and the test function:
testFunction(event){
e.preventDefault();
// do some things...
this.props.history.push('/test');
}
This works but I need to write both times the "/test" route (in the Link component and in the function).
Is there a way of getting the "to" prop so I don't have to write it twice?
If you use "withRouter" in your component:
import {Link, withRouter} from 'react-router-dom';
...
export default withRouter(TestComponent);
you can access the route's path by using:
this.props.match.path
Use this in your code:
testFunction(event){
e.preventDefault();
// do some things...
this.props.history.push(this.props.match.path);
}
When you use "withRouter" in your component you can access the match, location and history props of the route.
withRouter official documentation
match official documentation
Hope it helps!
In an application using react, redux and react-router, I'm using react-router-redux to issue navigation actions. I found that wrapping routes in a component with connect blocks navigation.
I made a sample with CodeSandbox that illustrates the issue: sample.
As is, the navigation doesn't work. However, if in ./components/Routes.jsx, this line:
export default connect(() => ({}), () => ({}))(Routes);
Is replaced by:
export default Routes;
It works.
Any idea how I could use connect in a component that wraps routes without breaking navigation?
See the troubleshooting section in react-redux docs.
If you change Routes.jsx export to:
export default connect(() => ({}), () => ({}), null, { pure: false })(Routes);
it will work.
This is because connect() implements shouldComponentUpdate by default,
assuming that your component will produce the same results given the
same props and state.
route changes, but props don't so the view doesn't update.
You could achieve same with withRouter hoc.
Not meant to be a duplicate.
I fixed it with withRouter like this
import { withRouter } from 'react-router-dom';
and
export default withRouter( connect(mapStateToProps)(App) );
See Redux, Router integration docs here
Have you ever encountered the warning message:
Warning: You cannot change <Router history>
Well use withRouter from react-router-dom
I have searched for this for so long because the Redux was recreating my App.jsx component which has <Route> </Route> as parents and this warning just freezes the routing in my app. I wanted to have React/Redux component, because I needed to pass authenticated props to the Route component, and redirect base on it, simple.
So import { withRouter } from 'react-router-dom'
and surround your component which is connected to redux with:
export default withRouter(connect(mapStateToProps)(App));
Something more:
Most of the times if you want to communicate with the router, takes some props, pass something else to it, get history, locations form it and you are using Redux in your app, surround this component with withRouter and you will have access to these properties as props.
This question already has answers here:
Programmatically Navigate using react-router
(9 answers)
Closed 5 years ago.
I´ve checked the following post and although it gives several different solutions not of them seens to solve my problem.
Using react-router V4 I need to programatically navigate from components deep insider my tree that will not have access to router props passed (history, url, params, etc.). What is the most straightfoward way of doing it ?
Any component in your tree, irrespective of its depth, can get access to the history, location and match props which are used by react-router. To do this you have to wrap the component in the withRouter HOC provided by react-router.
Code:
//other imports
import {withRouter} from 'react-router-dom'
//define component MyComponent here
export default withRouter(MyComponent);
Inside MyComponent defined above, you can access the history prop and redirect to any new url by using this.props.history.push(newURL); You can find more information at https://reacttraining.com/react-router/web/api/withRouter
The most straight forward way is to move history into separate file like so
history.js:
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export default history
and then in any other component:
import history from 'path/to/history.js'
...
someFoo(){
history.push({
pathname: '/new/url',
})
}
...
You also need to make sure you pass new history to your router to make it work