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.
Related
Is it possible to use Gatsby's navigate function to navigate to the same page?
For instance, I built a search component that lives on the navigation bar, therefor accessible on any page. Once users perform search, they get routed to the Search Results page via navigate(/search-results).
If they are on that page, and want to perform the search again, that navigate function does not work, hence no results display.
I'm aware I could do a window.location.reload() but wanted to see if there are other ways.
Gatsby's navigation (Link component or navigate function) doesn't support parameters per se as you want to.
From Gatsby's docs:
Neither <Link> nor navigate can be used for in-route navigation with a
hash or query parameter. If you need this behavior, you should either
use an anchor tag or import the #reach/router package—which Gatsby
already depends upon—to make use of its navigate function, like so:
So, that said, you have two approaches:
Importing the navigation from #reach/router:
import { navigate } from '#reach/router';
onClick = () => {
navigate('?foo=bar');
}
Using window.location as you pointed
Of course, the #reach/router will give you a smoother workaround.
I created a Gatsby/React instance sourcing from a Wordpress instance. I generate pages based on the page objects that I source from Wordpress. Everything works fine. I know that I have to put my content for the route / into src/pages/index.js. What would be the correct/canonical way to define one of my sourced page routes e.g./start as /?
Thanks in advance.
Basically you just call createPage with the path set to /. How you handle this in your CMS really depends on the structure you've set.
exports.createPages = ({ actions }) =>
actions.createPage({
path: "/",
component: path.resolve("./src/templates/some_template.jsx"),
})
I tend to prefer to require preceding and trailing slashes on slugs (e.g. /about/) in the CMS, which makes it easy to allow a content editor to leave just / for a page that is destined to become the home/root page. In the past I've also used home as a magic value that would be converted to / in gatsby-node.js, but it can cause confusion.
I carefully read the docs of next routing system.
It only mentions that I could achieve dynamic routing like this:
http://localhost:3000/level1/dynamicSlug
But I am trying to achive something like this:
http://localhost:3000/level1/level2/dynamicSlug
And I want level2 to be created dynamic too
Thanks so much !
It is possible to do nested scenarios according to your request in this way.
for example:
pages/
level1/
[dynamicSlug]/
- index.js // will match for /level1/1234
level2/
- index.js // will match for /level1/level2
- [dynamicSlug].js // will match for /level1/level2/1234
Or
pages/
level1/
[dynamicSlug]/
- index.js // will match for /level1/1234
level2/
- index.js // will match for /level1/level2
[dynamicSlug]/
- index.js // will match for /level1/level2/1234
You have 2 choices:
Using v9 Dynamic Routing by calling the folder as [dynSlag] and putting your page file inside.
Using custom server and routing, you will need to define a custom server, map your path to a specific next page.
I know this is a bit of an old post, but I'd just like to share my working response with NextJS v11.
I want dynamic routing at two levels. E.g.:
{siteroot}/dynamicPage
{siteroot}/dynamicUrlSection/dynamicPage
My folder structure is:
/pages/[section]/[page].tsx
/pages/[section]/index.tsx
This way, the "dynamicPage" path at the root is handled by index.tsx, and nested routes are handled by [page].tsx
BONUS INFO: I am working with Contentful as a CMS. I use a single content model for all the pages at both levels.
The model has "section" and "page" properties.
The entries that serve the root dynamic pages (i.e. /pages/[section]/index) have a compound value in the "page" property of {section}-index. I then have to be a bit smart in my client code:
if (!page) {
page = `${section}-index`;
}
await fetchData(section, page);
Using the example right from the NextJs documentation, I use this hack, maybe you could use it.
<Link href="/posts/[id]" as={`/posts/${subFolder}${id}`}>
"as" will have a value like /posts/nested_subfolder_file.md
And in the getPostData function, just do this little change:
const nestedPaths = id.split('_')
const fileName = `${nestedPaths.pop()}.md`
const fullPath = path.join(postsDirectory, ...nestedPaths, fileName)
I have an application which searches for some items and on finding them opensup a react application in new window with some params that are item specific.Now once i have my react application opened up in new window.I want to pass those params in the url throughout my application.
I searched for it but nothing helped.
Here is an example of my scenario :
Url with which I am opening the react application :http://localhost:3000/dashboard?instrumentId=75064&username=XYZ&appleturl=http%3A%2F%2Flxsdfeat1.global.abcecorp.net%3A7950%2FrmsDPPortal%2Fresources%2Fsapplauncher.jar&dsfhosturl=http%3A%2F%2Flxbeat1.global.bcecorp.net%3A7950%2FrmsasdfPortal
I want everything after 'dashboard' to be part of all the urls in my application.so that i can extract url,usernames in all the pages and make api requests using them.
Note: I am using react router for routing purpose
I passed that common url in this way and it works for my use case.
browserHistory.push(
{
pathname : "/calsummary",
search : searchParams
});
//or
browserHistory.push(
{
pathname : "/calsummary",
search : location.search//location object is which is available on window object,window.location
});
Hopefully this is a very simple question:
I want to create a string containing the full URL to a page on my site, like:
https://example.com/documents/1
Ideally I'd like to generate this in a react-redux connect()-ed container, in mapStateToProps(). Where the page is a grandchild of a react-router Route using browserHistory (so maybe I can get it from react-router or browserHistory somehow?) If necessary I'd do it in a full-on React class.
But I can't for the life of me find out how to do this. window (as in window.location) is always undefined in mapStateToProps() (no big surprise there) and in my view components' render() function.
So far I have only found ways to access the current route, e.g. "/documents/1", which is only a relative path and does not contain the site base url (https://example.com/)
So firstly, remember your code runs on client and server so any access to window needs to be wrapped in a check.
if (typeof window !== 'undefined') {
var path = location.protocol + '//' + location.host + '/someting'; // (or whatever)
} else {
// work out what you want to do server-side...
}
If the URL you generate shows in the DOM, and on the client you populate the store with this URL before the first render, you're going to get a checksum error. If you really want to avoid the error you can wait until componentDidMount() in your root component to get/set the url.
After componentDidMount you can have direct access to the origin location so that you can get the root url.
I use the below code in my JSX all the time so that i dont have to worry about the root path ex: dev env this would be localhost:3000/whatever, staging this will be AppStaging.heroku/whatever/..... and in production it would evaluate to www.myapp.com/whatever
`${window.location.origin.toString()}/whateverRoute/`
You Can try!!
window.location.origin
you can try the URL API. Take a look at this link for more details https://developer.mozilla.org/en-US/docs/Web/API/URL
const url = new URL("blob:https://mozilla.org:443/")
console.log(url.origin);
// Logs 'https://mozilla.org'