Replace the current url without reloading the page - reactjs

Using react 16, react-router 4.
My domain is suppose "https://www.xyz.c". I'm having anchor tag which should redirect to "https://www.xyz.c/some-path" without reloading the page.
I can implement it using <NavLink> and <Link> with to="/some-path". However, I need complete url to be shown in DOM (why? Well, on side note, I'm using itemProp for schema for which I want full path in anchor tag)
Implementing it with <a> and props.history tag like following causes to again replace with relative url, i.e. it becomes https://www.xyz.c/https://www.xyz.c/some-path in the url.
<a data-url="https://www.xyz.c/some-path" onClick={this.onClick}>Label</a>
onClick = e => {
e.preventDefault();
this.props.history.push(urlFromDataSet);
}
This seems impossible with <Navlink>, <Link> or <a> + props.history, since the policy is that history.replace, or history.push works on url with same origin. My url is also of same origin, however, I'm giving full path in href.
However, facebook is achieving the same in its header (Check on FB by going to home page, once loaded completely, then Click on your own profile button in header. It doesn't reload the page.)
How can we do that?

You are half there, you can use URL API to get the pathname of your data-url attribute then push it.
const url = new URL(dataUrl)
this.props.history.push(url.pathname)
More information about URL API: https://developer.mozilla.org/en-US/docs/Web/API/URL

Related

How add ability add query params for gatsby routes?

How to generate pages in gatsby that will allow you to add parameters to the routing like https://page1?someParam=param or https://page1/param
What I mean? When we navigate to page page1 in gatsby it work's fine, but what if I just want add uniq params for page for google analitics? so for this I want to have ability
add some additional params for the page from where I made redirect, but when I add
for page1 some params like https://page1?someParam=param or https://page1/param, it updated and show me just https://page1 instead.
I suppose that it's related to way how I created pages. Here is my code:
createPage({
path: `${localePrefix}/${slug}`, // so should I change it here in order to work as needed?
component: PageTemplate,
context: {
...context,
localizedPaths,
},
})
Can it be fixed with?
matchPath: path: ${localePrefix}/${slug}?*,
matchPath: path: ${localePrefix}/${slug}/*,
Recap:
My question is about why gatsby remove query params from pages?
https://some_site/some_page?some_param=323
translates into
https://some_site/some_page
https://page1?someParam=param or https://page1/param are not the same. While a query parameter (first case: ?someParam=param) is an optional value that doesn't change the rendered page (it doesn't point to any specific route hence it's not requesting any file). The second one (https://page1/param) is accessing a /pages/param route.
Since they are URL parameters, you don't need to change anything in your project, you just need to catch them using JavaScript. They are handled in thee:
const urlParams = new URLSearchParams(window?.location?.search);
Note: you can access directly location prop in Gatsby
If your project is replacing https://some_site/some_page?some_param=323 to https://some_site/some_page it's because some server-side configuration or a CDN, not because of Gatsby's behavior, like any other React project.

Dynamic route not working on page refresh with Next.js

I'm used Next.js but i have an error with dynamic route.
In my application I use getStaticPaths, getStaticProps and this:
<Link
href={`/offers/[id]?id=${offer.id}`}
as={`/offers/${offer.id}`}
>
<a>{offer.title}</a>
</Link>
When I click on this link, I have no problem with the dynamic route to display my page.
But when I refresh the same page, I get this message:
When I looked for a solution the answer was that my Link did not have the right setting when clicked on.
But now I don't click on the link, I just refresh my page.
I use Next.js 10.0.7
Since Next.js 9.5.3 there's no longer the need to use as for dynamic routes. Instead you can directly use the value to interpolate in href.
<Link href={`/offers/${offer.id}`}>
<a>{offer.title}</a>
</Link>
Alternatively, you can also use a different Link syntax by passing a URL object to it.
<Link
href={{
pathname: '/offers/[id]',
query: { id: offer.id }
}}
>
<a>{offer.title}</a>
</Link>
I had a similar problem. But I've been working with translations on the website.
So when I change selected language on any page it works fine, but as soon as I change language on any of the [id] page (item, article, etc.) I got the same error as you have.
In my case the problem was inside router.push() method I've used.
So when I pass router.pathname it returns /articles/[id] literally.
But actually I needed to use router.asPath which returns the correct URL path, such as /articles/abc123-456zczxc-7890-blablabla.
Here is an example from NextJS docs:
pathname: String - Current route. That is the path of the page in /pages, the configured basePath or locale is not included.
asPath: String - The path (including the query) shown in the browser without the configured basePath or locale.
NextJS API Reference Link

React Router Dom Prevent Prompt When Params Change

I am building a React Redux application and I am using <Prompt/> from react-router-dom to prevent a user from navigating away from a page when a specific icon is being rendered on the page.
It works fine except for when the params in the url change and then it fires the <Prompt/> when I don't want it to fire because I haven't actually tried to navigate anywhere. My url looks like:
http://localhost:8080/#/path/im/on?ids=1%2C24&from=1512518400000&searchRequest=e0007&to=1512604799000
When the ids in the url become successful, they are removed from the url but <Prompt/> is still fired.
Is there any way I can prevent <Prompt/> from firing when the url params change and the first part of the url stays the same? i.e. http://localhost:8080/#/path/im/on
Not sure if this is still relevant to you but you can do the following:
'message' prop in the Prompt component can either be a string or a function that returns a string or boolean.
<Prompt
message={(location) => {
return location.pathname.startsWith("your url")
? true
: `Are you sure you want to go to ${location.pathname}?`
}}
/>
if a function is passed to message prop then it will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
here is the documentation link: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Prompt.md

React Router 4 - How to append path to existing query

I am writing an webapp that only loads when you are on a url with a query, for example:
http://localhost/site/?runapp=1
And I want to use React Router 4 in the app, but when I add a Route with a path, such as:
<Route path="/somepage" component={somePage} />
And the user clicks a:
<Link to="somepage">
to load that Route the url gets converted to:
http://localhost/site/somepage
And on refresh, the app stops working as the query is gone. How can I make React Router 4 append the paths to the needed query? I know it doesn't look pretty, but essentially I need it to route like to this url:
http://localhost/site/?runapp=1/somepage
That would make it all work, I think.
Is there a way to achieve this?
EDIT: I realized that I can simply add the ?runapp=1 in every Link to get the url to be "correct", i.e:
<Link to="?runapp=1/somepage">
but it seems hacky and doesn't allow the Route to load.

how to check base url before routing using router in backbone.js

I am new to backbone.js, pardon me if the question seems silly.
I am routing to other pages using :
this.options.app.navigate( myNewURL, true);
this myNewURL gets appended to the current URL in the window but before doing that i want to make some checks on it.How do i fetch the current url and then append the newUrl to it and redirect?
eg:
current url : abc.com/firstString/SecondString
on navigation i want : abc.com/SecongString/myNewUrl
this firstString might or might not exist, so i have to make a check for it and remove it before redirection.
How can that be done?
The way I prefer navigation in Backbone.
Backbone.history.navigate('myNewUrl',{trigger:true}); //This will fire the router
Make trigger false to just change the route, but not execute the router.
In order to get the current url, you can use
Backbone.history.fragment();
References :
http://backbonejs.org/docs/backbone.html

Resources