using react router with next.js - javascript

I am learning how to use Next.js/React for my application. I am currently researching the topic of routing and I had a few questions. I know that you can use react-router for React (I used vue-router before). However, I do not know if I need to use react-router with Next.js and how I would use it if I could. I am currently using a pages directory to hold pages to redirect to. How can I redirect to different pages in React/Next?
Here is some sample code to implement it in:
Class Login extends Component {
state = {
user: {},
}
loginUser = (e) => {
loginUser(this.state.user)
.then(response => {
console.log(response);
if (response['username']) {
console.log('yippee!');
}
});
}
}
After yippee, I want to redirect to /home which is in the pages folder.

For your first question I need to say: No, you don't need react-router in Nextjs it will use something called file-system based router which you can read more about it here
So after you set up your routes if you want to Navigate to them you have two options:
first using the Link Component from next/link: more about it here
second using the router from next/router which you can Navigate around like useHistory from react-router: more about it here
example from the doc:
import { useRouter } from 'next/router'
function ActiveLink({ children, href }) {
const router = useRouter()
const style = {
marginRight: 10,
color: router.asPath === href ? 'red' : 'black',
}
const handleClick = (e) => {
e.preventDefault()
router.push(href)
}
return (
<a href={href} onClick={handleClick} style={style}>
{children}
</a>
)
}
export default ActiveLink
So in your case, using this is how you can redirect:
import { withRouter } from 'next/router'
Class Login extends Component {
state = {
user: {},
}
loginUser = (e) => {
loginUser(this.state.user)
.then(response => {
console.log(response);
if (response['username']) {
console.log('yippee!');
//here is what you need:
this.props.router.push('/your-route');
}
});
}
}
export default withRouter(Login)

Related

How to implement Broadcast Channel API in React

I need to check when the user opens a new tab if there any other tabs are opened in the browser. So when we can able to find that there are no tabs opened already, then we need to do some operations if not we can just leave
How can we achieve this using Broadcast Channel API?
Especially how to implement this concept in React?
Thanks in Advance!!
I will answer the second part of your question "Especially how to implement this concept in React?"
I will give an example of implementing multi-tab logout.
Create a file somewhere in your App , I created mine in a folder called Auth and created a file named auth.js
import { BroadcastChannel } from 'broadcast-channel';
const logoutChannel = new BroadcastChannel('logout');
export const login = () => {
localStorage.setItem("token", "this_is_a_demo_token")
history.push('/app/dashboard')
}
export const logout = () => {
logoutChannel.postMessage("Logout")
localStorage.removeItem("token", 'this_is_a_demo_token' )
window.location.href = window.location.origin + "/";
}
export const logoutAllTabs = () => {
logoutChannel.onmessage = () => {
logout();
logoutChannel.close();
}
}
As you can see, I use this dependency npm i broadcast-channel for simplicity with my React App.
Create an instance called logoutChannel with the name 'logout'. On logging out , the instance sends a post message ('Logout').
Use the logoutAllTabs function in your App.js file as follows
import React, { useEffect } from "react";
import { logoutAllTabs } from "./auth/auth";
import Router from "./routes";
function App() {
useEffect(() => {
logoutAllTabs()
}, [])
return (
<>
<Router/> // All routes here
</>
);
}
export default App;
Kindly follow this tutorials to see the above implementation in action :
1.) https://youtu.be/mb5nuUbvfvM
2.) https://dev.to/demawo/how-to-logout-of-multiple-tabs-react-web-app-2egf

React - Need help converting path to string so users get redirected to Stripe when clicking img

So let me explain what's going on. I have this component called PaymentAccountLandingPage and in that component I import and render this component ConnectedAccountsButton which is a Stripe button that I created using a Stripe image and essentially making it just like button. So I want users to be redirected to the landing page for creating an account with Stripe when they click img/button. The problem is to do that I need to make an axios call with createAcctLink so that it returns a pathname that contains an accountId that I need to have in the path (I XXXXXX'd out the acctId below obviously). But I need that info in the path because someone else on my team parses at a later point when they get redirected back the problem is the response data that comes back from response.item is the following:
https://connect.stripe.com/express/onboarding/XXXXXXXXXXXX
Note it is not a string and I even used the toString method to TRY and turn it into a string but no luck. Does anyone have any other solutions? I don't want to use window.location.assign() or window.location.href because I already know how to do it that way but the reason why I want to figure out another way is because that takes 10-15 seconds to redirect users to Stripe. The reason why I want to use Link react-router-dom is because it's fast and I know there's also Redirect but either way I need the path to be a string so that's my issue. If anyone has any solutions or workarounds that'd be awesome. Here's my ConnectedAccountsButton:
import React from "react";
import connectbutton from "#assets/images/stripe/ConnectedAccountsButton.png";
import { createAccountLink } from "../../services/connectedAccountsService";
import { Link } from "react-router-dom";
class ConnectedAccountsButton extends React.Component {
state = {
path: "",
};
componentDidMount() {
createAccountLink()
.then(this.onAccountLinkSuccess)
.catch(this.onAccountLinkError);
}
onAccountLinkSuccess = (response) => {
let pathUrl = response.item.toString();
console.log("Success Response:", pathUrl);
this.setState(() => {
return {
path: pathUrl,
};
});
};
onAccountLinkError = (err) => {
console.error("Error Response: ", err);
};
render() {
return (
<Link to={this.state.path}>
<img
src={connectbutton}
style={{ width: "200px", cursor: "pointer" }}
alt="Connected Accounts Link"
/>
</Link>
);
}
}
export default ConnectedAccountsButton;
I'm answering my own question because I figured out the solution with a friends help. The strange thing is we used typeof on response.item and it was already a string. There's no reason this shouldn't have worked but it didn't. We even checked the React Dev Tools and sure enough in state was the correct path but for some reason when I clicked the img it would send me to one of my error routes.
This is what ended up working:
import React, { useState, useEffect } from "react";
import connectbutton from "#assets/images/stripe/ConnectedAccountsButton.png";
import { createAccountLink } from "../../services/connectedAccountsService";
import debug from "sabio-debug";
import { useHistory } from "react-router-dom";
const _logger = debug.extend("ConnectedAccountsButton");
const ConnectedAccountsButton = () => {
const [url, setUrl] = useState("");
const history = useHistory();
useEffect(() => {
createAccountLink().then(onAccountLinkSuccess).catch(onAccountLinkError);
}, []);
const redirectConnectedAccount = () => {
history.push(url);
};
const onAccountLinkSuccess = (response) => {
_logger("Success Response", response.item);
setUrl(response.item);
};
const onAccountLinkError = (err) => {
_logger("Error Response", err);
};
return (
<img
src={connectbutton}
style={{ width: "200px", cursor: "pointer" }}
alt="Connected Accounts Link"
onClick={redirectConnectedAccount}
/>
);
};
export default ConnectedAccountsButton;

Using client-only routes with page templates coming from Contentful

Goal
I am looking to use client-only routes for content under a certain URL (/dashboard). Some of this content will be coming from Contentful and using a page template. An example of this route would be {MYDOMAIN}/dashboard/{SLUG_FROM_CONTENTFUL}. The purpose of this is to ensure projects I have worked on at an agency are not able to be crawled/accessed and are only visible to 'employers' once logged in.
What I have tried
My pages are generated via gatsby-node.js. The way of adding authentication/client-only routes has been taken from this example. Now the basics of it have been setup and working fine, from what I can tell. But the private routes seem to only work in the following cases:
If I'm logged in and navigate to /dashboard
I'm shown Profile.js
If I an not logged in and go to /dashboard
I'm shown Login.js
So that all seems to be fine. The issue comes about when I go to /dashboard/url-from-contentful and I am not logged in. I am served the page instead of being sent to /dashboard/login.
exports.createPages = async ({graphql, actions}) => {
const { createPage } = actions;
const { data } = await graphql(`
query {
agency: allContentfulAgency {
edges {
node {
slug
}
}
}
}
`);
data.agency.edges.forEach(({ node }) => {
createPage({
path: `dashboard/${node.slug}`,
component: path.resolve("src/templates/agency-template.js"),
context: {
slug: node.slug,
},
});
});
}
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions;
if(page.path.match(/^\/dashboard/)) {
page.matchPath = "/dashboard/*";
createPage(page);
}
};
My auth.js is setup (the username and password are basic as I am still only developing this locally):
export const isBrowser = () => typeof window !== "undefined";
export const getUser = () =>
isBrowser() && window.localStorage.getItem("gatsbyUser")
? JSON.parse(window.localStorage.getItem("gatsbyUser"))
: {};
const setUser = (user) =>
window.localStorage.setItem("gatsbyUser", JSON.stringify(user));
export const handleLogin = ({ username, password }) => {
if (username === `john` && password === `pass`) {
return setUser({
username: `john`,
name: `Johnny`,
email: `johnny#example.org`,
});
}
return false;
};
export const isLoggedIn = () => {
const user = getUser();
return !!user.username;
};
export const logout = (callback) => {
setUser({});
call
};
PrivateRoute.js is setup the following way:
import React from "react";
import { navigate } from "gatsby";
import { isLoggedIn } from "../services/auth";
const PrivateRoute = ({ component: Component, location, ...rest }) => {
if (!isLoggedIn() && location.pathname !== `/dashboard/login`) {
navigate("/dashboard/login");
return null;
}
return <Component {...rest} />;
};
export default PrivateRoute;
dashboard.js has the following. The line <PrivateRoute path="/dashboard/url-from-contentful" component={Agency} />, I have tried a couple of things here - Statically typing the route and using the exact prop, using route parameters such as /:id, /:path, /:slug :
import React from "react";
import { Router } from "#reach/router";
import Layout from "../components/Layout";
import Profile from "../components/Profile";
import Login from "../components/Login";
import PrivateRoute from "../components/PrivateRoute";
import Agency from "../templates/agency-template";
const App = () => (
<Layout>
<Router>
<PrivateRoute path="/dashboard/url-from-contentful" component={Agency} />
<PrivateRoute path="/dashboard/profile" component={Profile} />
<PrivateRoute path="/dashboard" />
<Login path="/dashboard/login" />
</Router>
</Layout>
);
export default App;
And finally agency-template.js
import React from "react";
import { graphql, Link } from "gatsby";
import styled from "styled-components";
import SEO from "../components/SEO";
import Layout from "../components/Layout";
import Gallery from "../components/Gallery";
import GeneralContent from "../components/GeneralContent/GeneralContent";
const agencyTemplate = ({ data }) => {
const {
name,
excerpt,
richDescription,
richDescription: { raw },
images,
technology,
website,
} = data.agency;
const [mainImage, ...projectImages] = images;
return (
<>
<SEO title={name} description={excerpt} />
<Layout>
<div className="container__body">
<GeneralContent title={name} />
<Gallery mainImage={mainImage} />
<GeneralContent title="Project Details" content={richDescription} />
<div className="standard__images">
<Gallery projectImages={projectImages} />
</div>
<ViewWebsite>
<Link className="btn" to={website}>
View the website
</Link>
</ViewWebsite>
</div>
</Layout>
</>
);
};
export const query = graphql`
query ($slug: String!) {
agency: contentfulAgency(slug: { eq: $slug }) {
name
excerpt
technology
website
images {
description
gatsbyImageData(
layout: FULL_WIDTH
placeholder: TRACED_SVG
formats: [AUTO, WEBP]
quality: 90
)
}
richDescription {
raw
}
}
}
`;
export default agencyTemplate;
I assume that gating content from a CMS is possible with Gatsby but I might be wrong given it is an SSG. I may be misunderstanding the fundamentals of client-only. The concepts in React and using Gatsby are still very new to me so any help or guidance in achieving the goal would be appreciated.
What I ended up doing
So the answer I marked was the one that 'got the ball rolling'. The explanation of what was happening with state and requiring either useContext or redux helped me understand where I was going wrong.
Also, the suggestion to use web tokens prompted me to find more information on using Auth0 with the application.
Once I had got out of the mindset of creating pages using Gatsby (Through a template, via gatsby-node.s), and instead doing it in a 'React way' (I know Gatsby is built with React) by handling the routing and GraphQL it became clearer. Along with the authentication, all I ended up doing was creating a new <Agency /> component and feeding the data from GraphQL into it and updating the path with my map().
return (
<>
<Router>
<DashboardArea path="/dashboard/" user={user} />
{agencyData.map(({ node }, index) =>
node.slug ? (
<Agency key={index} data={node} path={`/dashboard/${node.slug}`} />
) : null
)}
</Router>
</>
);
I assume that in your PrivateRoute component, you're using the isLoggedIn check incorrectly. importing and using isLoggedIn from auth.js will run only initially and will not act as a listner. What you can do is that store the value of isLoggedin in global state variable like(useContext or redux) and make a custom hook to check for the login state. Secondly avoid accessing localStorage directly, instead use the global state managment (useContext, redux) or local state managment (useState, this.state).
Note: that when ever you go to a route by directly pasting url in browser, it always refreshes the page and all your stored state is reinitialized. This may be the reason why you may be experiencing this issue. The browser does not know that you had been previously logged in and therefore it always validates once your application is mounted. What you can do is that you can store isLoggedIn state in browser's localstore. Personally I like to use redux-persist for that.
export const useGetUser = () => { //add use infront to make a custom hook
return useSelector(state => state.gatsByUser) // access user info from redux store
};
export const handleLogin = ({ username, password }) => {
//suggestion: don't validate password on client side or simply don't use password,
//instead use tokens for validation on client side
if (username === `john` && password === `pass`) {
dispatch(setUserInfo({
username: `john`,
name: `Johnny`,
email: `johnny#example.org`,
isLoggedIn: true,
}));
return true;
}
return false;
};
// adding 'use' infront to make it a custom hook
export const useIsLoggedIn = () => {
//this will act as a listner when ever the state changes
return useSelector(state => state.gatsByUser?.isLoggedIn ?? false);
};
export const logout = (callback) => {
const dispatch = useDispatch(); // redux
dispatch(clearUserInfo());
};
Now in private route do
import React from "react";
import { navigate } from "gatsby";
import { useIsLoggedIn } from "../services/auth";
const PrivateRoute = ({ component: Component, location, ...rest }) => {
const isLoggedIn = useIsLoggedIn();
if (!isLoggedIn) {
return navigate("/dashboard/login");
}
return <Component {...rest} />;
};
export default PrivateRoute;
It looks like you're server-side rendering dashboard/[url] in gatsby-node.js/createPages()? IIRC those routes will have higher precedence than dynamic routes (which you specify with #reach/router in dashboard.js).
Plus, the content of those routes are currently publicly available. If you want to keep them truly private, you should query Contentful graphql API directly on the client side (via fetch() or use apollo client, urql, etc.), instead of relying on Gatsby's graphql server.
I would do the follows:
Removing the dashboard/[url] portion in your gatsby-node.js
Configure your web host so that all routes matches '/dashboard/*' will redirect to '/dashboard'
If you happen to host your static site on Netlify, you'd create a _redirects with this, assuming you configure Gatsby to create nice url:
# /static/_redirect
/dashboard/* /dashboard 200
A possible simpler way that match your current setup is gating content at web host level. You can configure nginx to protect /dasboard/* with basic auth. However maintaining/updating password is a pain & modern hosting solution don't really allow user to configure that.
Netlify offers its own authentication solution that you could look into.
I've had the same issue earlier and I couldn't get exact functionality with Private Routes.
In my case, I created two separate Layouts for Public and Private Routes and built the authentication to Private Layout. Logged-in user data were linked to a redux store (First I used Context, then moved to Redux). In Private routes with the Private Layout, it redirected the guest users to the Login page and redirected them to the same page after login.
Private layout is something like this:
import React from "react";
import { navigate } from "gatsby";
import { useSelector } from "react-redux";
const PrivateLayout = ({children}) => {
const isLoggedIn = useSelector(state => state.user.isLoggedIn);
useEffect(() => {
if (!isLoggedIn) {
// redirect the user to login page.
// I'm sending the current page's URL as the redirect URL
// so that I can take the user back to this page after logging in.
}
}, [isLoggedIn])
if (!isLoggedIn) return null;
return <>
{...header}
{children}
{...footer}
</>
}
export default PrivateLayout;
Not sure if this workaround suits you. If it does, I can give you more info.

Next.js: Router.push with state

I'm using next.js for rebuilding an app for server side rendering.
I have a button that handles a search request.
In the old app, the handler was this one:
search = (event) => {
event.preventDefault();
history.push({
pathname: '/results',
state: {
pattern: this.state.searchText,
}
});
}
In the results class, I could get the state date with this.props.location.state.pattern.
So now I'm using next.js:
import Router, { withRouter } from 'next/router'
performSearch = (event) => {
event.preventDefault();
Router.push({ pathname: '/results', state: { pattern: this.state.searchText } });
};
In the results class, I use
static async getInitialProps({req}) {
return req.params;
}
I'm not sure if I have to add this to my server.js:
server.get('/results', (req, res) => {
return app.render(req, res, '/results', req.params)
})
However, the function getInitialProps throws an error because req is undefined. Long text, short question: how to pass state or params to another page without using GET parameters?
In next.js you can pass query parameters like this
Router.push({
pathname: '/about',
query: { name: 'Someone' }
})
and then in your next page (here in /about page), retrieve the query via the router props, which needs to be injected to Component by using withRouter.
import { withRouter } from 'next/router'
class About extends React.Component {
// your Component implementation
// retrieve them like this
// this.props.router.query.name
}
export default withRouter(About)
If you want your url remain clean, make a small addition to Prithwee Das's answer like below.
Router.push({
pathname: '/about',
query: { name: 'Someone' }
}, '/about');
Now you can access props in your component using props
...
const YourComponent = (props) => {
useEffect(() => {
console.log(props.router.query.name);
}, [props.router.query]);
return (
<React.Fragment>
...
</React.Fragment>
);
};
...
I don't know whether this supports SSR, but I had to do it as follows to avoid the error cannot read property 'query' of undefined.
This uses useRouter hook to get access to the url, imported as below.
import { useRouter } from 'next/router'
Assume you want to pass data {name:'Someone'} from Component A to Component B.
In Component A,
const router = useRouter();
router.push(
{ pathname: "/path_of_component_b", query: { name: "Someone" } },
"path_of_component_b"
);
In Component B,
const router = useRouter();
useEffect(() => {
alert(router.query.name); // Alerts 'Someone'
}, [router.query]);
If you want 'clean' urls, one way to go about it is to add onClick handler to your link and store required information in context/redux store. It easy to implement if you already have one.
<Link href='...'>
<a onClick={()=>{dispatch(....)}}>Link<a/>
<Link>

Resolve Nextjs URL to a selected component

From what I understand Nextjs resolves URLs by mapping them to their respective file in pages folder. So pages/about-us.js will be accessable via href="/about-us".
I want to create multiple languages but don't wanna duplicate the necessary components/JS files. So assuming I have an about-us.js with following content:
<Head title={meta}/>
<Nav/>
<MainContent language={lang}/>
<Footer/>
How can I map /pl/about-us to the /about-us.js in the root of pages without creating another about-us.js in /pages/pl/..?
One of the solution I can think of is to pass the language as a query param
Example
// code for page/about-us.js page
import { withRouter } from 'next/router';
const AboutUs = ({ router }) => {
const { lang } = router.query;
return <div>Welcome to next.js! Language = {lang}</div>;
};
export default withRouter(AboutUs);
so If you got to about-us?lang=pl it will show
Welcome to next.js! Language = pl
Or instead of parsing language inside every page, you can use custom app.js with the code something like this
// custom _app.js
import React from 'react'
import App, { Container } from 'next/app'
export default class MyApp extends App {
static async getInitialProps({ Component, router, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx)
}
return { pageProps }
}
state = {
language: undefined
};
componentDidMount() {
const { router } = this.props;
this.setState({ language: router.query.lang });
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} language={this.state.langugage} />
</Container>
)
}
}
so every page will have language passed as a param.
Hope this helps.
UPDATE:
to make a custom routing you need to check disabling file-system routing and write some custom server routing

Categories

Resources