How to force user to exit app with react-router-dom - reactjs

I am new to react-router-dom and web development. I am creating a PWA on mobile browser, I could not find a way to navigate the user to exit the app like in native mobile app
what happened was the page was navigating over and over again until it hits the last stack of the history then it will close the app
I know how to listen to route changes, how do I force user to exit the app if they're in a specific route without going back to previous history

It depends on what do you mean by "forcing a user to exit the app"?
What is the trigger and what the effect?
Trigger can be button click for example, and effect can be redirect.
let's say that the auth user on route { /app } and by clicking -
import { Redirect } from 'react-router-dom';
<button
onClick={()=> <Redirect to="/" }
/>
But from your question it sounds like you want to use your location as trigger and do something according to that (if you don't familiar with hooks it can translated to componentDidMount/Update) -
React.useEffect(()=> {
if (props.location.pathname === '/') {
// Do Something here...
}
}
,[props.location])
Here is the full { location } react-router doc https://reacttraining.com/react-router/web/api/location
Do notice that { location } have
state: {
[userDefined]: boolean
}
method, maybe it will help you with user flow process

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 force Gatsby to redirect a specific URL path to an external site?

I have a Gatsby site and due to some specific requirements, I need to redirect anyone who attempts to hit a specific URL path, for which there is no page, to an external site. This URL path is not a page within the site, but it's something that a user may be inclined to type due to documentation that is out of my control.
Here's an example: Let's say the site is located at https://www.example.com. A user may visit https://www.example.com/puppies, which does not exist. My file structure does not contain a src/pages/puppies.js file. However, when that URL is entered, I need to redirect the user to another site altogether, such as https://www.stackoverflow.com.
I haven't used Gatsby to that extent to know it has a configuration for this, so someone else may correct me. The way I would handle this is through the hosting provider where your app is.
For example, if you are using Netlify:
Create a _redirects file with the following content:
/* /index.html 200
Or
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
This will cause all https://yourwebsite.com/IDontHaveThisRoute to fallback to /index.html where your .js is loaded.
I provided the Netlify example only to give you the basic idea of how it can be done through the hosting provider of your choice. I would look into configurations I can put into redirects where my domain is deployed.
Thanks to Paul Scanlon he mentioned using onRouteUpdate in Gatsby and it works like a charm
import { navigate } from 'gatsby';
export const onRouteUpdate = ({ location }) => {
if (location.pathname === '/dashboard') {
navigate('/dashboard/reports');
}
};
This question helped point me in the right direction. I was able to get it to work using Gatsby's componentDidMount() to force a redirect as shown below, using a new file called puppies.js to "catch" the path typed by the user:
// puppies.js
import React, { Component } from 'react'
class Puppies extends Component {
componentDidMount() {
window.location.replace("https://www.stackoverflow.com");
}
render() {
return <div />
}
}
export default Puppies

React Native: How do you get a Moneris transaction to return to app?

I'm processing a transaction with Moneris in my React Native app in a WebView. The URL in my WebView contains the credentials of my Hosted PayPage Configuration as URI parameters. When creating that configuration on the Moneris site, I need to provide the URL for the hosted paypage to redirect to once the transaction is complete. When I enter something like https://www.google.ca/ as the callback, it works fine, but I don't know what callback URL I'd need to enter to return to my app.
What I Want To Know:
What is the callback URL I'd need to use in order to return to a React Native app?
WebView is just a component inside your app, so you are never leaving your app. First, confirm that page is rendered in a WebView as opposed to launching browser as a separate app and opening a page there (in this case you can't go back to your app programmatically). Then, if you are actually using a WebView component, you could, for example, do the following: add NavigationState listener to your WebView, and read the url the WebView navigates to and take action accordingly
class MyComponent extends React.Component{
onNavigationStateChange = (navState) => {
if (navState.url === 'https://www.yoursite.com') {
// user just got redirected to requested site
// do something in react-native app now, for example
// close this component and show another one
}
}
render(){
return <View>
<WebView
...
onNavigationStateChange={this.onNavigationStateChange}
/>
</View>
}
}

What type of navigation in React works well with login authentication?

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.

Render different components on client and server side

I am currently developing a website where I have used react, react-router and redux. We are doing Server side rendering and using react router on server as well. Now I have a case where i want client side to render different component than server side. I want like this.
Client Side
<Route path="welcome/:id" component={Home} />
Server Side
<Route path="welcome/:id" component={App} />
I have use case like when user click's an image i want to open a modal with contents and recommend images . when user click's on recommended images same modal should fill up the details and i want to change the route as well. Same route when opened in new window should open an html page for facebook and google to scrap meta tags from it.
So either I render different component on client and server. But that too has a problem because then i need to find a way to turn off client side react router when server is serving the rendered page.
Or in client side generate a pseudo route change which changes url but doesn't render a component.
Check if window is present and conditionally set the component you want to use like this:
let Handler;
if (typeof window !== 'undefined') {
Handler = Home;
} else {
Handler = App;
}
return <Route path="welcome/:id" component={Handler} />
The troublemaker in me wants to know why you're doing this :)
check process.env.Browser
let Handler;
if (process.env.browser) {
Handler = Home;
} else {
Handler = App;
}
return <Route path="welcome/:id" component={Handler} />

Resources