Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Vladimir Kutepov
@frenzzy
@LucaGabi the answer is here: kriasoft/universal-router#184
Rui Carneiro
@carneiror_gitlab

Hi all! Did anyone here had "circular dependencies" issues when using universal-router and react?

// routes.ts
import React from "React";
import AdminPage from "./admin";
import HomePage from "./homepage";

export const router = new UniversalRouter([
  {
    name: "homepage",
    path: "/",
    action: () => <Homepage/>
  },
  {
    name: "admin",
    path: "/:admin",
    action: () => <AdminPage/>
  }
], {});

export const urls = generateUrls(router);

// admin.tsx
import React from "React";
import { urls } from "./routes";

const AdminPage: FunctionComponent = () => {
  const url = urls("homepage");

  return (
    <div>
      <a href={url}>Homepage</a>
      <br/>
      <h1>Hello World</h1>
    </div>
  )
};
export default AdminPage;

In this example I can't use generateUrls without a circular dependencies. Routes need Pages , Pages need Urls, Urls need Routes.

Vladimir Kutepov
@frenzzy
@carneiror_gitlab probably you can give url generator to your pages through router context without the need to import routes inside route. For example:
const routes = [ // or import routes from 'routes.js'
  { name: 'home', path: '', action: ({ url }) => <a href={url('admin')}>Go to admin page</a> },
  { name: 'admin', path: '/admin', action: () => <h1>Admin Page</h1> }
]

const router = new UniversalRouter(routes)
const url = generateUrls(router)
const { pathname } = window.location

router.resolve({ pathname, url })
Rui Carneiro
@carneiror_gitlab
It's an option. Will try! Thx @frenzzy
quanganhtran
@quanganhtran

I'm trying out version 9, but it seems that

export interface RouteParams {
    [paramName: string]: string | string[];
}

does not reflect the path params correctly. e.g. optional path can be undefined

and not sure when it is a string[]
Vladimir Kutepov
@frenzzy
@quanganhtran they are an array when there are * or + modifiers https://github.com/pillarjs/path-to-regexp#modifiers
like /:foo* or /:bar+
Vladimir Kutepov
@frenzzy
btw, there are no key for optional path at all, value can't be undefined
quanganhtran
@quanganhtran
but the indexed type does not prevent you from accessing non-existing key. it assumes all string key
gkn06
@gkn06
How to import universal router in typescript?
Vladimir Kutepov
@frenzzy
@gkn06 the same as in javascript:
import UniversalRouter from 'universal-router';

const routes = [{ path: '/demo', action: () => 'Hello!' }];
const router = new UniversalRouter(routes);
router.resolve('/demo').then(console.log);
gkn06
@gkn06
No luck 😒 am getting this error
Cannot find module 'universal-router'.ts(2307)
gkn06
@gkn06
@frenzzy its fixed. I need to set moduleResolution to node is tsconfig
thanks a lot @frenzzy
Vladimir Kutepov
@frenzzy
:tada:
Ender Minyard
@genderev
hey all
I have an app that generates divs from Javascript. After the page loads, I want each div to have its own permalink. Is this the right solution?
Right now I have an anchorlink for each div in the page, but I don't know how to make it a permalink. When I paste the url with the hash/fragment/anchor link in a new tab, its like the anchor link isn't there.
Vladimir Kutepov
@frenzzy
<div id="foo"></div> and /index.html#foo should just work
Ender Minyard
@genderev
thanks @frenzzy

I think I need this

{
        path: '/:id',
        action: (context) => `<h1>Post #${context.params.id}</h1>`
      }

I want to generate user profiles for each user based on the url query. Is that what /:id does? (if :id was a username for example)

Ender Minyard
@genderev
{
          path: '/:username',          // www.example.com/admin/users/john
          action: () => 'User Profile'
        }
I think I answered my own question
What does action: () => 'User Profile' mean?
Vladimir Kutepov
@frenzzy

@genderev the router executes action method of a route and returns its result:

import UniversalRouter from 'universal-router'

const routes = [
  { path: '/:username', action: (ctx) => `<h1>User Profile: ${ctx.params.username}</h1>` },
]

const router = new UniversalRouter(routes)

router.resolve({ pathname: '/genderev' }).then(result => {
  document.body.innerHTML = result
  // renders: <h1>User Profile: genderev</h1>
})

https://github.com/kriasoft/universal-router/blob/master/docs/getting-started.md

Ender Minyard
@genderev
Awesome. How do you render more complex things? For example, if you want to add CSS.
Vladimir Kutepov
@frenzzy
@genderev check out https://github.com/kriasoft/react-starter-kit and https://github.com/kriasoft/react-firebase-starter
they both use universal-router and shows how you can use it
Ender Minyard
@genderev
Do you think they're useful if you're using neither Firebase nor React?
Vladimir Kutepov
@frenzzy
If you are looking for more complex examples, then yes, why not
dpyzo0o
@dpyzo0o
Does anyone has a working demo using create-react-app with universal-router?
Vladimir Kutepov
@frenzzy
@dpyzo0o as far as I know https://github.com/kriasoft/react-firebase-starter uses both CRA and UR
dpyzo0o
@dpyzo0o
@frenzzy Thanks
Adrian Edwards
@MoralCode
Not sure if this chat is still active, but I'm looking for a way to warn a user that they may have unsaved changes before leaving the page and all i'm getting with online searches is solutions for react-router. Has anyone implemented this behavior with UniversalRouter?
Adrian Edwards
@MoralCode
(i also posted this as a stackoverflow question (https://stackoverflow.com/questions/63875381/react-universalrouter-prevent-user-leaving-the-page) since i think this is something that would be useful to have documented somewhere (also in case i forget to reply here)
Vladimir Kutepov
@frenzzy
@MoralCode hi! You just need to show the confirmation before changing the url.
See an example if you are using history module: https://github.com/ReactTraining/history/blob/master/docs/blocking-transitions.md
Adrian Edwards
@MoralCode

@frenzzy awesome, thank you so much, i'll give that a try.

Also does anyone know if universalRouter has a way to designate a folder for static assets such as the favicon that are located in /public?

Abhinav Das
@theabhinavdas
hey, how to integrate google analytics with universal-router?
Neven DREAN
@ndrean
So about Redirection and the middleware approach. I made the test . In the renderRoute method, choose "router" or "routerNext" and change to mode "A" (redirection) or mode "B" (without redirection). The "routeNext" fails. Now I made this to lazy render the components. If I can't use it, I can't split the code so much.
Neven DREAN
@ndrean
Marcus Wong
@pc-mwong
Hello, I need some clarification. Are the context custom properties immutable? Seems like once i add context.customProperty it cannot be modified
LuckyArthas
@LuckyArthas
@vbabenko
Sajeel Khawaja
@SajeelWaien

Hello! I need help, I am using universal router and it works fine on my localhost but as on deployment I get error for a specific route not all of them only when I refresh the page or land directly on it, its giving internal server error due to a variable not found.
This is the link https://buscatuchoza.com/sitemap/municipility/La-Habana
While this link works fine: http://localhost:3001/sitemap/city/La-Habana/La-Habana-Del-Este

Below is the route code

export default {
  path: '/sitemap',

  children: [
    {
      path: "",
      async action({ params, store, query }) {

        return {
          title: title,
          description: "Venta de Casas en Cuba Busqueda - Buscar casas en venta - BuscaTuChoza Site Map",
          component: <Layout>
            <Sitemap />
          </Layout>,
        };
      },
    },
    {
      path: '/municipility/:statename',

      async action({ params, store, query }) {
        let municipility = params.statename.split("-").join(" ")
        let title = `Venta de Casas en ${municipility} Busqueda - Buscar casas en venta - BuscaTuChoza Site Map`

        return {
          title: title,
          description: title,
          component: <Layout>
            <State municipility={municipility}/>
          </Layout>,
        };
      },
    },
    {
      path: '/city/:statename/:cityname',

      async action({ params, store, query }) {
        let state = params.statename.split("-").join(" ")
        let city = params.cityname.split("-").join(" ")
        console.log("CITY", state, city)
        let title = `Venta de Casas en ${city} Busqueda - Buscar casas en venta - BuscaTuChoza Site Map`

        return {
          title: title,
          description: title,
          component: <Layout>
            <City state={state} city={city}/>
          </Layout>,
        };
      },
    }
  ]
};
joe Jankowiak
@jrj2211

Hello, I'm having issues with my middleware not running:

const router = new UniversalRouter([
  {
    path: '',
    action: async () => {
      console.log('here');
    }
  }
]);

I'm running in a dev environment (so localhost) and when I go to http://localhost I see the print out 'here'. If I go to any other page such as http://localhost/test the middleware never runs. Shouldn't '' run for every URL?

joe Jankowiak
@jrj2211
I found it runs the middleware if I add an empty "children: []". Not sure if that's a bug or intended functionality.
Apoorva Gupta
@Apoorva32561884_twitter
Nice article, thanks for sharing informative content. I like the content of the post.
Salesforce Training
Nikhil Sharma
@sharmanikhil7028_gitlab
Nice article, thanks for sharing informative content. I like the content of the post. cyber security course
visheshpaliwal9
@visheshpaliwal9
Write Great article. You are such a Great blogger and your website is inspiration for me to start a blog. This article is very helpful for us
Aws course
kritishah1
@kritishah1
Thank you for sharing such a good information. Very informative and effective post.salesforce admin training
Adrian Edwards
@MoralCode

Does UniversalRouter support delegating entire routes (like /admin) to other routing tools for them to handle? i have an app that uses universalrouter and i want to add react-admin to it, but it seems like the router part of my redux state (managed by UniversalRouter) is not compatible with what react-admin expects it to be. From https://marmelab.com/react-admin/CustomApp.html#using-an-existing-redux-provider "That means that react-admin will work out of the box inside another Redux application - provided, of course, the store is compatible.".

Is it possible to essentially "sandbox" react-admin so that universal-router essentially passes off tesponsibility to react-admin for '/admin/ routes? or is there something else i need to do to make the two work together?

TL;DR has anyone used universal-router with react-admin before?
Vladimir Kutepov
@frenzzy
@MoralCode you can use a middleware and call react-admin route handler inside it, i.e.
const route = {
  path: '/admin',
  children: [],
  action: (context) => {
    return reactAdminRouteHandler(context.pathname)
  },
}