is possible to implement relative paths on https://name.github.io/project in React for gh-pages, using React Router, as I receive errors.
I used import {withRouter} from 'react-router-dom'; and export default withRouter(componentName); to forward routing props from Router to targeting component, and I receive them.
I tried implemented like this Links:
<li><Link to={{pathname: this.props.match.url + '/new-post'}}>New Post</Link></li>
and used this modality this.props.match.url to obtain current path, but I receive errors.
Has anybody some suggestions?
It can be configured in react router history:
history.js
import createBrowserHistory from 'history/createBrowserHistory';
const history = createBrowserHistory({
basename: 'project',
});
export default history;
Related
Is it possible to create a global history file to manage the createBrowserHistory() on react-router-dom v5?
I know the V5 has the useHistory() as a way to get the history. But is it possible to retrieve the history from anywhere, like for cases where I am not using a function component?
On V4 I could create a file history.js:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
It works on V4
https://codesandbox.io/s/react-router-v4-nfwr0
It doesn't work on V5 - It updates the URL but redirects to not-found
https://codesandbox.io/s/react-router-v5-not-working-jlrep
As the doc says you should use the v4 of history to work on react-router v5.
https://github.com/ReactTraining/history
Documentation for version 4 can be found on the v4 branch. Version 4 is used in React Router versions 4 and 5.
I solved this by doing this.See what i done
Create a file like before
This is the code
import {createBrowserHistory} from 'history';
import store from 'store';
export default createBrowserHistory({
basename: store ? store.getState().productionBaseUrl : ''
});
The reason why i import Redux is the project does not pulish on nginx root folder.So i should add a basename.If you do not neet it,you can remove it.
Then you can use it in your own coponnet. How to use? Let me show your the code.
// if my history in src/router/
import history from 'router/history';
history.push(`${your router address}`)
Attention
The history's push method can pass an object like the origin props.But it's refresh when in the child router always. So pass a string when use it.
I am trying to understand the difference between BrowserRouter and Router of the react-router-dom (v5) package and what difference it makes for my example below.
The documentation says:
BrowserRouter
A that uses the HTML5 history API (pushState,
replaceState and the popstate event) to keep your UI in sync with the
URL.
Source: https://reacttraining.com/react-router/web/api/BrowserRouter
Router
The common low-level interface for all router components. Typically
apps will use one of the high-level routers instead: BrowserRouter, HashRouter, MemoryRouter, NativeRouter, StaticRouter
Source: https://reacttraining.com/react-router/web/api/Router
From what I understand is that I should be using BrowserRouter for my HTML5 browser apps and I have been doing this so far.
history.push(...) example:
I am trying to perform a history.push('/myNewRoute') within a thunk:
import history as './history';
...
export function someAsyncAction(input) {
return dispatch => {
fetch(`${API_URL}/someUrl`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ input }),
}).then(() => {
history.push('/myNewRoute');
}).catch((err) => {
dispatch(setError(err));
})
};
};
history is defined as this module:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
and the history is also passed to my router:
import { BrowserRouter as Router } from 'react-router-dom';
import history as './history';
...
const App = () => (
<Router history={history}>
...
</Router>
);
Problem: history.push() will update the URL in the browser bar but not render the component behind the route.
If I import Router instead of BrowserRouter, it works:
// Does not work:
import { BrowserRouter as Router } from 'react-router-dom';
// Does work:
import { Router } from 'react-router-dom';
BrowserRouter ignores the history prop as it handles the history automatically for you. If you need access to the history outside of a react component, then using Router should be fine.
You can access history via the useHistory hook let history = useHistory(); to perform history.push() for BrowserRouter.
Looking at the HTML5 History API documentation, it seems that the history API preserves state for the user automatically. Say you are at page 1 initially and page 1 has a page outlook A. You performed some actions that changes the page 1 outlook to B. If you now moves to page 2, when you click the back button on the browser, you will be direct back to page 1. History API preseves your state so it knows to render outlook B to you, so that is the advantage of using BrowserRouter. Though I am not 100% sure, I suppose Browser doesn't come with this functionality and in which case it will render outlook A when you get directed back to page 1. This is not true. I am not sure about the difference.
I have the same issue.
BrowserRouter and useHistory() hook have been used for my component. And createBrowserHistory() has been used for redux-saga. But, the page has not moved by redux-saga such as your case.
Adding to that, my source has been developed using BrowserRouter, I don't want to replace it to Router component.
As my poor investigating, I found that both history objects are different. (I compared them with if and ==.) I guess it is the reason.
To solve it, I save the reference of the history object got by useHistory() to some global utility code, and use it in redux-saga code. Then, it works well.
I don't think this is the best way, but I couldn't find the best and official way yet.
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
Is there any way to create an action in your MobX store, which pushes your app to a new url using react router v4, e.g. this.props.history.push...
I constantly get a history undefined error, but am unsure how to access the history from my store.
The history push called from the component itself does work though..
many thanks! (this is driving me crazy..)
Since I stumbled across the same issue, I'll share my solution. I just put the RouterStore into its own file in my stores directory, then if I needed access to history or location or whatever, I would import the routing store into the store I was currently working in.
./stores/routing.ts
import { RouterStore } from 'mobx-react-router'
export default new RouterStore()
./stores/other-store.ts
import routing from './routing'
export class OtherStore {
#action
doSomething = () => {
routing.push('/new-route')
}
}
export default new OtherStore()
./index.ts
import { Router } from 'react-router-dom'
import { Provider } from 'mobx-react'
import createBrowserHistory from 'history/createBrowserHistory'
import { syncHistoryWithStore } from 'mobx-react-router'
import otherStore from './stores/other-store'
import routing from './stores/routing'
const browserHistory = createBrowserHistory()
const stores = {
otherStore,
routing,
}
const history = syncHistoryWithStore(browserHistory, routing)
ReactDOM.render(
<Provider {...stores}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById('root'),
)
You can use mobx-react-router to put react-router in a mobx store and then use it by injecting it in components.
You can also pass the router store as a constructor argument to your other stores that need it. This way you have the router history instance available in your mobx store.
I would like to add a simpler solution that does not require any additional libraries. React Router version is 5.2
Among my stores i've created a HistoryStore.js with the following code:
import { createBrowserHistory } from 'history';
export class HistoryStore {
history = createBrowserHistory();
}
Then I create an instance of it in my contexts.js file but you could do it right away.
export const history = new HistoryStore();
After that you import it in your index.js and pass it as a history prop to the Router.
That's it. Now you could import this store into any other and use it there. When you use useHistory hook in your component it gets this history object, so your history in synchronized.
//startup file
import {BrowserRouter} from 'react-router';
let root=(<BrowserRouter>
//Some components
</BrowserRouter>);
ReactDOM.render(Root, document.getElementById("app"));
// function to navigate or route
import createBrowserHistory from 'history lib createBrowserHistor';
const history = createBrowserHistory();
let browseTo=function(path){
history.push({pathname: path})
})
After calling above Function only URL path changing actual route is not perform.
Like URL localhost:8080 changes to localhost:8080/login not routing to login component.
https://github.com/ReactTraining/react-router/issues/4059
browserHistory is not exposed by react-router in v4, only in v2.