Use react history object to change last browser's URL - reactjs

Im currently trying to use the history.push() object from:
https://github.com/ReactTraining/history
Im having problem to change last's URL of browser when the browser's back button is clicked.
When I use the history.push(...) the current browser's URL changes; there is a way to avoid this? Or just using window object I can make this work?
My application is not a Single Page-Application; the code:
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
const testUrl = 'http://test.com'
history.push(testUrl);
window.addEventListener('popstate', (event) => {
history.go(testUrl);
});

You could use pushState or replace. pushState adds a new entry, whereas replace modifies the current.
#see https://developer.mozilla.org/de/docs/Web/Guide/DOM/Manipulating_the_browser_history
as I can see from your module history/createBrowserHistory, you are using this module, which should be fully compatible with the native implementation.

Related

Change the Route without Fetching that routes content

So I know this doesn't sound like a good case, but I'm trying only to change the browser link on React using React Router without loading that page it selfs, in case the user reloads the page then fetches it because it matches the route, I'm trying to use this so when the user saves the product on the preview page to not redirect to the new id so I can fetch the data, this will be consuming, rather I want to manipulate the URL so that everything is on its place.
I tried this using useNavigate, I think and will do the same, I think I saw some websites have something similar implemented.
Here again what I do have for the start, this fetches the page:
import { useNavigate } from "react-router-dom";
...
const to = useNavigate();
...
<p onClick={() => to('/product/stackoverflow-shirt')}>!don't fetch the content</p>
I found the solution to my problem, but not with React Router, rather the native method that Window provides.
Here we go:
window.history.replaceState({}, ‘’, ‘/newSlug’)

How to implement a "render-as-you-fetch" pattern for routes in React

The new Relay hooks API has put a focus on the React pattern of "render-as-you-fetch" and so far I am really liking this. Relay's useQueryLoader and usePreloadedQuery hooks make implementing this most of the time pretty straight forward.
I am however, struggling to find a good pattern on how to implement this pattern when it comes to routing. There are two typical situations that I find makes this difficult to implement.
Situation A:
User loads a home page (example.com/)
User go deep down one part of the app tree (example.com/settings/user/security/authentication)
They then click on a link to take them to a totally unrelated part of their app (example.com/blog/post-1)
Situation B:
User uses the URL bar to go to a section of the app instead of using a link (example.com/blog/post-1)
With these examples there are two outcomes, either the user goes to a route (example.com/blog/post-1) either via a nest child component or directly via the URL. So the way we are fetching data for this route must support both of these approaches.
I assume we would want to trigger the fetch as early as possible for this route, so when the user clicks on the link or as soon as we detect this route on page load.
There are three ideas I can think of to implement this:
Use a fetch-then-render pattern instead (such as Relay's useLazyLoadQuery hook)
Store a function (say in Context) and have all links for this route call this function in their onClick method, and also have a useEffect for this route that calls the function if there is no data loaded, or the reference for the query is stale
Use render-as-you-fetch functions but implement them to support fetch-then-render also
Approach 1:
This defeats the purpose of render-as-you-fetch pattern however is an easy way out and more likely to be a "cleaner" way to implement fetching data for a route.
Approach 2:
In practice I have found this really hard to implement. Often the link to go to the route is disconnected from part of the component tree where the component renders the route is. And using a Context means that I have to manage different loadData functions for specific routes (which can be tricky when variables etc are involved).
Approach 3:
This is what I have been doing currently. In practice, it often results in being able to pass the load data function to a near by component, however if the route is accessed by a disconnected component, by the URL, or a page reload etc then the components falls back to calling the load data function in a useEffect hook.
Does anyone have any other ideas or examples on how they implemented this?
An update on this topic, React Router v6 recently introduced support for route loaders, allowing preload Relay queries based on routing.
Example:
import { StrictMode, Suspense } from "react";
import ReactDOM from "react-dom/client";
import {
createBrowserRouter,
Link,
RouterProvider,
useLoaderData,
} from "react-router-dom";
import graphql from "babel-plugin-relay/macro";
import {
loadQuery,
PreloadedQuery,
RelayEnvironmentProvider,
usePreloadedQuery,
} from "react-relay";
import { environment } from "./environment";
import { srcGetCurrentUserQuery } from "./__generated__/srcGetCurrentUserQuery.graphql";
const getCurrentUser = graphql`
query srcGetCurrentUserQuery {
viewer {
id
fullname
}
}
`;
const Test = () => {
const data = usePreloadedQuery(getCurrentUser, preloadedQuery);
const preloadedQuery = useLoaderData() as PreloadedQuery<srcGetCurrentUserQuery>;
return (
<Suspense fallback={<>Loading...</>}>
<Viewer preloadedQuery={preloadedQuery} />
</Suspense>
);
};
const router = createBrowserRouter([
{
element: (
<>
{"index"} <br /> <Link to={"/test"}>Go test</Link>
</>
),
path: "/",
},
{
element: <Test />,
path: "test",
loader: async () => {
return Promise.resolve(
loadQuery<srcGetCurrentUserQuery>(environment, getCurrentUser, {})
);
},
},
]);
ReactDOM.createRoot(document.getElementById("root")!).render(
<StrictMode>
<RelayEnvironmentProvider environment={environment}>
<RouterProvider router={router} />
</RelayEnvironmentProvider>
</StrictMode>
);
More information about React Router loaders here: https://reactrouter.com/en/main/route/loader
I've also been struggling with understanding this. I found these resources particularly helpful:
Ryan Solid explaining how to implement fetch-as-you-render
The ReactConf 2019 Relay demo
The Relay Issue Tracker example
What I understand they aim for you to achieve is:
Start loading your query before and outside of the render path
Start loading your component at the same time as the query (code splitting)
Pass the preloaded query reference into the component
The way it's solved in the Relay demo is through something they call an "Entrypoint". These are heavily integrated into their router (you can see this in the Issue Tracker example). They comprise the following components:
A route definition (e.g. /items)
A lazy component definition (e.g. () => import('./Items'))
A function that starts the query loading (e.g. () => preloadQuery(...))
When the router matches a new path, it starts the process of loading the lazy component, as well as the query. Then it passes both of these into a context object to get rendered by their RouterRenderer.
As for how to implement this, it seems like the most important rules are:
Don't request data inside components, request it at the routing or event level
Make sure data and lazy components are requested at the same time
A simple solution appears to be to create a component that is responsible for collecting the data, and then rendering the respective component. Something like:
const LazyItemDetails = React.lazy(() => import('./ItemDetails'))
export function ItemEntrypoint() {
const match = useMatch()
const relayEnvironment = useEnvironment()
const queryRef = loadQuery<ItemDetailsQuery>(relayEnvironment, ItemDetailsQuery, { itemId: match.itemId })
return <LazyItemDetails queryRef={queryRef} />
}
However there are potential issues that the Issue Tracker example adds solutions to:
The lazy component may have previously been requested so should be cached
The data fetching sits on the render path
Instead the Issue Tracker solution uses a router which does the component caching, and the data fetching at the same time as the route is matched (by listening to history change events). You could use this router in your own code, if you're comfortable with maintaining your own router.
In terms of off the shelf solutions, there doesn't appear to be a router that implements the patterns required to do fetch-as-you-render.
TL;DR Use the Relay Issue Tracker example router.
Bonus: I've written a blog post about my process of understanding this pattern

Replace only last path part in URL

I'm using react-router-dom v4.3.1.
For example: I have the following URL
http://localhost:3000/url1/url2/url3
I need to replace only last route in URL: /url3 → /mynewroute3
How to do it with history?
Use history.push
someMethod = () => {
const { history } = this.props;
history.push(`/url1/url2/url_new`); // change url3 to "url_new"
}
this.props should have history in it if you were using withRouter in the root component.
SO: Using React Router withRouter
Programmatically navigate with React Router
When doing history.push(...) the Router picks up the change and acts on it.
Only change the last part of the URL;
location.pathname.split('/').slice(0,-1).join('/') + '/newPath'
Regex:
location.pathname.replace(/[^/]*$/, newPath)
The above takes the current window location path, cut the part after the last / (including) and adds a new string (the new path)
I know this question is asked for React Router v4 but I was trying to perform same thing with React v5 and find this answer. For future reference, in React Router v5, I was able to perform this using the following;
history.push('./mynewroute3'); // Changes last part
history.push ('./../mynewroute3'); // /url1/url2/url3 => /url1/mynewroute3

React: How to reference an image url in require

I have a data file api that has bunch of images url stored locally
const url =[
{ title:img1,
img_src="./img/img1.png"
},
{ title:img2,
img_src="./img/img2.png"
},
{ title:img3,
img_src="./img/img3.png"
}
]
And using react/redux I pass the url state as props to my react components.Next I want to display them in my components by using require
<img src=require(?)/>
What's the appropriate syntax here? I've used es6 template string ${this.props.urls.img_src} but it throws an error that it couldn't resolve the path. I've tried to require("./img/img1.png") just to test to rule out broken path and it worked. But still wouldnt work if you reference it using a prop.
Solution
After researching, and thanks to Rei Dien for the input, I now can use variables in require by using context require
<img src={require("./img/"+this.props.img_src)}/>
Since you passed the url in the props, you can do this :
this.props.url.map(n => {
return (
<img src={n.img_src}/>
)
})
this will diplay all the images.
since require works in static mode during build process on node only so follow following steps.
1) take all image urls and store them in a javascript file
so
//imageURLs.js
import image1 from "path_to_image_file_1";
import image2 from "path_to_image_file_2";
import image3 from "path_to_image_file_3";/**do like this for all images stored locally, image1, image2,.. are the image identifiers(title in your case) you would get in api call**/
export const urls = {image1, image2, image3};
//image usage file
read api for identifier and
import imageURLs from './imageURLs.js';
<img src={imageURLs[image_id_from_api]}/>

Using react-router history to change path adds ? before #

I'm using react router in my redux web app when i try to update the route using
this.props.history.push('/route')
It adds a ? to the address like so
https://website.com/?#/route
When it should look like this
https://website.com/#/route
This causes my single page application to reload.
Things i tried:
upgrading react router to latest (2.0.1, currently using 1.0.3) didn't help
we're using hash history, switching to browser history didn't help
Is it because you're using <form> with React, and it's submitting a form.
See this answer for a better explanation: https://stackoverflow.com/a/32570827/5498949
Try with this
import { Router, Route, BrowserHistory } from 'react-router';
let bHistory = BrowserHistory({
queryKey: false
});
It will diable the random string appearing in the route path.

Resources