I have a react applicatie running in a Amazon S3 bucket, it is available here: This is the homepage of the app, the user can search ships in the search bar.
The app produces a link in the dropdown menu that looks like this:
However when the user clicks on the link you don't see the details page but the user is redirected to this page without CSS.
Locally is everything working fine.
My route component looks like this:
export class Routes extends React.Component {
render() {
return (
<div>
<Route exact path={HOME_PAGE} component={Home}/>
<Route path={HOME_PAGE + "/details/:id"} component={Details}/>
<Route path={HOME_PAGE + "/form/:mode"} component={Edit}/>
<Route path={HOME_PAGE + "/form/:mode/:id"} component={Edit}/>
<Route path={HOME_PAGE + "/csvForm"} component={CsvForm}/>
</div>
);
}
}
I have build a prefix for the HOME_PAGE path that looks like this:
export const HOME_PAGE = (ENVIRONMENT == "DEVELOPMENT") ? "" : "/url"
This sets the homepage path for either development or production environment.
I was thinking of an other way to pass the ship id to the details page, maybe with a GET parameter. So the route will look something like this HOME_PAGE + /details?id=5c335682379b4d7a6ea454a8.
But I don't know if react-router supports that kind of parameter, maybe someone has a beter solution to solve this problem. Just by playing around on the website, I hope I have given enough information to understand the structure of the site.
If you're using react router v4, for every Route that you defined, react-router will pass three props:
Match
Location
History
If you would like to access the params (which is under /:someParams), you can access the Match props by using match.params.someParams
And if you prefer the query string, you can use the Location props by using location.search which is a string so that in your case it'll return ?id=5c335682379b4d7a6ea454a8. You'll have to process the string by using qs to get your id value.
You can see the detail over here: https://reacttraining.com/react-router/core/api/Route/route-props
So in your case this would be the solution:
On your parent
<Route path={HOME_PAGE + "/details"} component={Details}/>
Your your Details Component
import qs from 'query-string'
const Details = ({location}) => {
const {search} = location
const queries = qs.parse(search) // you should have the query string object
return (
<div>{queries.id}</div>
)
}
Related
I want to create dynamic pages in gatsby but I don't know what the full url name would be.
createPage({
path: '/account/orders/:id',
matchPath: '/account/orders/:id',
component: path.resolve('./src/templates/order.tsx'),
});
I thought the code written would be okay to visit page with any value of 'id' but while building the development bundle it gives an error
account\orders\:id contains invalid WIN32 path characters
The ':id' value can be anything so I dont want to use looping method to create the page. What could be done?
Taking into account that:
You don't want to loop through pages
You will never know the value of the id
Your only chance is to use client-only routes through the file system route API.
In your case, assuming that your "unknown" page will be under /account/orders you should create a folder structure such: src/pages/account/orders/[...].js. The [...].js notation stands for the file system route for an undefined value.
In the [...].js file you can just create something like:
import React from "react"
import { Router } from "#reach/router"
import Layout from "../components/Layout"
import Profile from "../components/Profile"
import Default from "../components/Default"
import CustomOrderComponent from "../components/CustomOrderComponent"
const Orders = () => {
return (
<Layout>
<Router basepath="/account/orders">
<Profile path="/profile" />
<CustomOrderComponent path='/:id' />
<Default path="/" />
</Router>
</Layout>
)
}
export default Orders
From the docs:
Briefly, when a page loads, Reach Router looks at the path prop of
each component nested under <Router />, and chooses one to render
that best matches window.location (you can learn more about how
routing works from the #reach/router documentation). In the
case of the /orders/profile path, the Profile component will be
rendered, as its prefix matches the base path of /orders, and the
remaining part is identical to the child’s path.
In the above scenario, CustomOrderComponent will render your variable id (:id).
This is the content of my app.json
I have the following state :
const params = new URLSearchParams(window.location.search)
const [checkboxes,setCheckkoxes] = React.useState({
circular: Number(params.has('circular')?params.get('circular'):0),
});
Its initial value is based on whether it has the param ('circular') on the URL.
<HashRouter basename = {process.env.PUBLIC_URL}>
<Switch>
<Route exact path = "/">
<Root/>
</Route>
<Route exact path = {"/Pesquisar/:searchField/:page"} component = {withRouter(Pesquisa)}>
</Route>
<Route exact path = {"/documento/:id"} component = {Documento}>
</Route>
<Route exact insecure component={ Insecure }/>
</Switch>
</HashRouter>
When I was using Router instead of HashRouter my state was working properly, when I pass the query param 'circular = 1' in the URL, my state was properly signalled to 1. However, after changing it to HashRouter it's not working anymore. Its value is always Zero. What's happening, why am I not able to access window.location.search params after switching from Router to HashRouter?
URLParams not able to work with react HashRouter that is a known issue wich is been reported on github.
In version v3.0.0-beta.1 they added two new props for complete customisations:
- getSearchParams: Function [optional]
Enables you to customise the evaluation of query-params-string from the url (or) any other source. If this function is not set, the library will use window.location.search as the search query-params-string for parsing selected-values. This can come handy if the URL is using hash values.
- setSearchParams: Function [optional]
Enables you to customise setting of the query params string in the url by providing the updated query-params-string as the function parameter. If this function is not set, the library will set the window.history via pushState method.
See docs
I'm using Gatsby and I want build a single page site, so without create pages. For achieve this I edited gatsby-node.js with the following code:
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path === "/") {
page.matchPath = "/*"
createPage(page)
}
}
in that case, each request is re-routed to the index.js page, which is the only one.
Then, in the index.js page I have:
const IndexPage = () => {
const intl = useIntl()
const locale = intl.locale
return (
<BGTState>
<BlogState>
<Layout>
<Router>
<Home path={`${locale}/`} />
<Section path={`${locale}/:sectionSlug`} />
<Collection path={`${locale}/:sectionSlug/:collectionSlug`} />
<Season
path={`${locale}/:categorySlug/:collectionSlug/:seasonSlug`}
/>
<Product
path={`${locale}/:categorySlug/:collectionSlug/:seasonSlug/:prodSlug`}
/>
<Blog path={`${locale}/blog`} />
<Article path={`${locale}/blog/:articleSlug`} />
<NotFound default />
</Router>
</Layout>
</BlogState>
</BGTState>
)
}
as you can see, I have different routers that load a specific component based on the url.
I have prefixed each path with the current locale to match the correct path.
This mechanism is working fine for the home page only, but for the other links doesn't work. Infact, if I visit something like:
http://localhost:3001/en/category-home/prod-foo
which must load the Collection component, the site simply redirect to:
http://localhost:3001/en
and display the Home component again.
What I did wrong?
UPDATE
Page Structure:
As you can see I have just the index.js which handle all requests as I configured in the gatby-node.js.
If I remove the localization plugin, at least using this configuration:
{
resolve: `gatsby-plugin-intl`,
options: {
// Directory with the strings JSON
path: `${__dirname}/src/languages`,
// Supported languages
languages: ["it", "en", "ci", "fr"],
// Default site language
defaultLanguage: `it`,
// Redirects to `it` in the route `/`
//redirect: true,
// Redirect SEO component
redirectComponent: require.resolve(
`${__dirname}/src/components/redirect.js`
),
},
},
and I don't prefix the url with intl.locale, everything is working fine. But adding redirect: true in the plugin configuration, and prefixing the link with the locale, the site redirect me to the home component.
If you are creating a SPA (Single Page Application, notice the single) you won't have any created pages but index. You are trying yo access to a /category page that's not created because of:
if (page.path === "/") {
page.matchPath = "/*"
createPage(page)
}
That's why your routes don't work (or in other words, only the home page works).
Adapt the previous condition to your needs to allow creating more pages based on your requirements.
I'm using Gatsby and I want build a single page site, so without
create pages. For achieve this I edited gatsby-node.js with the
following code:
It's a non-sense trying to build a SPA application with Gatsby (without creating pages) but then complaining because there's not collection page created.
Make sure that you understand what you are doing, it seems clearly that you need to create dynamically pages for each collection, season, and product so your approach to create SPA won't work for your use-case.
It's possible to keep just index.js without overcomplicating thing? I
just want to understand why my code isn't working 'cause I've passed
the correct url... Removing the localization Gatsby works, so I
suspect there is a localization problem
The only way that http://localhost:3001/category-home/prod-foo (removing the localization) could be resolved is by creating a folder structure such /pages/category-home/prod-foo.js (since Gatsby extrapolates the folder structure as URLs), so, if you want to use localization using your approach, add a structure such en/pages/category-home/prod-foo.js and es/pages/category-home/prod-foo.js (or the whatever locale), and so on. In my opinion, this is overcomplexitying stuff since, for every category, you'll need to create 2 (even more depending on the locales) files.
Gatsby allows you to create dynamic pages and interpolate the locale automatically using built-in plugins on the process, creating each file for the specifically defined locales.
I wonder what type of navigation works well with login authentication? Right now i use conditional rendering for certain pages or components to display and through
if (this.state.loggedIn) {
return <UI loggedIn={this.state.loggedIn} showUser=
{this.state.showUser} logout={this.logout.bind(this)} />;
};
i can render something after the validation. What would it look like if i wanted to render a couple of more different pages? Should i put a state on each page that will change on onclicks and cause the app to render desired page?
Thank you lads
This is an issue which nearly every modern application must tackle. Because of this, many libraries have already solved these issues for you. Take this code for example which uses react-router:
In my example I am showing you what the routes would look like in a routes.js file and then a separate file for what the acl would look like. The acl is a function which is passed into the onEnter of each route you want to protect. You can call it anything you like.
routes.js
import React from 'react';
import { hashHistory, Router, Route, IndexRoute } from 'react-router';
import { acl } from './util/acl-util';
import AppContainer from './containers/app-container';
import DashboardPage from './pages/dashboard-page';
export default class Routes extends React.Component {
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={AppContainer}>
{/* NON-AUTH ROUTES */}
<Route
path="login"
components={{
main: LoginPage,
aside: null,
header: this.getHeader,
}}
/>
{/* AUTH-REQUIRED ROUTES */}
<Route
onEnter={acl}
path="dashboard"
components={{ main: DashboardPage }}
/>
</Router>
);
}
}
acl-util.js
import { hasAuth } from './auth-util';
export function acl(nextState, replace) {
const { pathname, search } = nextState.location;
if (!hasAuth(theState)) {
window.alert(
'Please Log in!'
);
replace(`/login?loginRedirect=${encodeURIComponent(pathname + search)}`);
}
}
I threw this example together from cutting out part of my code that won't apply directly to this concept - and therefore this code won't run as is. You'll need to define your pages, and set up a store etc.
You'd need to define a hasAuth function which can look into your state and determine whether a user is authenticated. For my hasAuth function I am looking for a jwt token and parsing the date, if the date is still in the future, I know they are still authed and any subsequent rest api calls will work.
I know you weren't asking for a certain library, but I recommend this because the app I took this code from has dozens of routes and the acl function also implements a role matrix which looks at what a user can and cannot do based on their jwt token. Our application is pretty massive and this approach keeps it organized.
Without having something like react-router, you're right, you'd need to manually manage which page is showing and manually check for auth state in each component or make a parent component to do it. In my example the "parent component to manage it" is react-router and my onEnter method called acl. In traditional applications acl stands for access control list - you can expand the code in whichever way you like.
edit:
as someone mentioned in a comment about . Your frontend application is only as secure as the backend service it is grabbing data from or posting data to. In my example, the react code attempts to mirror the auth state in the jwt token. But, at the end of the day, your real security will only be provided by your back end services. Just because the frontend thinks a user can be logged in, shouldn't mean the backend should assume they are - you need backend authentication since all frontend application state can be modified by technical users.
I am trying to set a Route path with a query string. Something in the lines of:
www.mywebsite.com/results?query1=:query1&query2=:query2&query3=:query3
I would than transition to the "Results" component like so:
<Route path="/" component={Main}>
<IndexRoute component={Home} />
<Route path="results?query1=:query1&query2=:query2&query3=:query3"
component={SearchResults} />
</Route>
In the SearchResults container I would like to be able to have access do query1, query2 and query3 params.
I have not been able to make it work. I get the following error:
bundle.js:22627 Warning: [react-router] Location
"/results?query1=1&query2=2&query3=3" did not match any routes
I tried following the steps in the following guide: (Section: What about query string parameters?)
https://www.themarketingtechnologist.co/react-router-an-introduction/
Can I get some help here?
If you are using React Router v2.xx, you can access the query parameters via the location.query object passed in to your Route component.
In other words, you could rework your route to look like the following:
<Route path="results" component={SearchResults} />
And then inside your SearchResults component, use this.props.location.query.query1 (similar for query2 and query3) to access the query parameter values.
EDIT: This is still the case for React Router v3.xx.
If you're using React Router >= v4 location.query is not available anymore. You can plug-in an external library (like https://www.npmjs.com/package/query-string), or use something like this:
const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar
(just keep in mind that URLSearchParams() is not supported by Internet Explorer)