Routing with react-router-dom using react vite - reactjs

Blockquote
How do I route to the next page or another page using VITE?

I have the same problem, using vite, to redirect to another page we need to import the following lib:
import { navigate } from 'vite-plugin-ssr/client/router';
Don't need to create const variables, but have a caveat, this just work using Client Routing, on the other hand, you can use:
window.location.href = YOUR ROUTE
See the documentation for more information.

In Vercel this can be done by adding a rewrite to config file in the root of the project called
vercel.json
https://vercel.com/docs/configuration
Add rewrites for all routes to the file that point to '/' or '/index.html'
{
"rewrites": [{ "source": "/(.*)", "destination": "/" }]
}
or
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
Refence: Vite.js React Build Not Redirecting On Netlify And Vercel

All your routing can be done via react-router-dom
Use Navigate, Redirect or useNavigate provided by react-router-dom
Please go through the docs and try to implement before asking

Related

problem with service worker accessing django admin when serving react as main url [duplicate]

I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index.
Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue.
This is a snippet from my nginx conf:
location / {
try_files $uri $uri/ =404;
}
location /api/ {
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
location /admin/ {
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
and my django urls config:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(routers.urls))
]
Any ideas on how I could proceed would be appreciated
It sounds like React is intercepting the onClick event of the links and preventing the browser from handling it normally.
You can try altering the link tags so that they prevent React from doing that:
<a href="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</a>
/* Or if using react router */
<Link to="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</Link>
Is there a way to exclude routes in react so it will only display if the path is "/"…
How are the routes added or configured in React? They should be changed to use the format I illustrated above, or deleted if you don't want them to display at all.
… or is there something in nginx/django config I can change to overcome this issue.
Your nginx configuration is written correctly. You can test it here.
I think i found the solution.
1- update your react-scripts to ^v4
2- add urls you don't want to be cached to service-worker.js file:
registerRoute(
({ request, url }) => {
...
if (
url.pathname.startsWith('/admin') ||
url.pathname.startsWith('/api')
) {
return false;
}
...
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);

React and django cache issue

I have a react and django app which is being served behind nginx. The /admin route and /api routes both point to uwsgi. However when loading these routes the react app is served unless a hard refresh of the page is peformed. It seems like react is serving all routes instead of just the index.
Is there a way to exclude routes in react so it will only display if the path is "/" or is there something in nginx/django config I can change to overcome this issue.
This is a snippet from my nginx conf:
location / {
try_files $uri $uri/ =404;
}
location /api/ {
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
location /admin/ {
uwsgi_pass uwsgi;
include /etc/nginx/uwsgi_params;
}
and my django urls config:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(routers.urls))
]
Any ideas on how I could proceed would be appreciated
It sounds like React is intercepting the onClick event of the links and preventing the browser from handling it normally.
You can try altering the link tags so that they prevent React from doing that:
<a href="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</a>
/* Or if using react router */
<Link to="/admin/" onClick={() => { location.href = "/admin/" }}>Admin</Link>
Is there a way to exclude routes in react so it will only display if the path is "/"…
How are the routes added or configured in React? They should be changed to use the format I illustrated above, or deleted if you don't want them to display at all.
… or is there something in nginx/django config I can change to overcome this issue.
Your nginx configuration is written correctly. You can test it here.
I think i found the solution.
1- update your react-scripts to ^v4
2- add urls you don't want to be cached to service-worker.js file:
registerRoute(
({ request, url }) => {
...
if (
url.pathname.startsWith('/admin') ||
url.pathname.startsWith('/api')
) {
return false;
}
...
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);

Express/React app refresh issue on Heroku

My React app with Express backend is hosted on Heroku, and all of the routing works as expected until the page refreshes. Refreshing the page either programmatically, or with the refresh button the page returns:
Failed to load resource: the server responded with a status of 404 (Not Found)
The back and forward buttons (which work before refreshing) cease to work and the only way to get the app back is to navigate to the "/". Everything works correctly then until the next refresh.
My server routes :
router.use("/api/skus", skuRoutes);
router.use("/api/categories", categoryRoutes);
// serve static files if in production
if (process.env.NODE_ENV === "production") {
router.use(express.static("client/build"));
router.get("*", (req: Request, res: Response) => {
res.sendFile(
path.resolve(__dirname, "..", "client", "build", "index.html")
);
});
}
I have read many, many other similar questions on here and many tutorials on using react router on Heroku, but I haven't found a solution that works for me.
I have already tried the solutions that use a static.json file:
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
, and adding the create-react-app buildpack to Heroku, but these do not work for me.
GitHub repo here.
Current deployment here.
The issue was fixed by changing my BrowserRouter to a HashRouter. Now refreshes work perfectly.

After deploy projects configured with Vercel or Nextjs rewriting can't find assets path

I have the following structure to use one domain to multiple projects:
A repo that contains a single vercel.json file to configure path to others projects
A repo that contains a home app example
A repo that contains a checkout app example
The vercel.json works pretty great and is deployed in nizen.com.br, here is how is it:
// vercel.json
{
"rewrites": [
{
"source": "/checkout",
"destination": "https://checkout.nizen.com.br/checkout"
},
{
"source": "/",
"destination": "https://home.nizen.com.br"
}
]
}
So if we go to nizen.com.br we get the home app example without styles and a bunch of errors in console trying to get the assets of home.nizen.com.br in nizen.com.br and the same happens to checkout app.
Here is one of the similar errors that appear in console on Home app:
And here is the checkout app:
About the app next.config.js files, only Home app stays untouched and Checkout app has a basePath added with value "/checkout" as follows:
// Checkout app next.config.js
module.exports = {
reactStrictMode: true,
basePath: "/checkout",
};
I have tried to use the Next rewrites in hope that will solve the problem but it didn't work.
// example of rewrite that I did
module.exports = {
async rewrites() {
return [
{
source: "/",
destination: "https://home.nizen.com.br",
},
];
},
};
I tried to pass :path* and :path in source and destination, as well use fallback and even change the destination to checkout app to see if something change and none of that worked.
If I got to https://home.nizen.com.br the app runs perfect and same to checkout. What am I doing wrong?
I have solved this question changing the strategy. Instead of using a repo with vercel.json to route the micro-frontends, I'm using the home app as the project hosted in nizen.com.br and it's next.config.js file is the one who makes the magic happen!
//Home App next.config.js file
module.exports = {
reactStrictMode: true,
async rewrites() {
return {
fallback: [
{
source: "/checkout",
destination: "https://checkout.nizen.com.br/checkout",
},
{
source: "/checkout/:path*",
destination: "https://checkout.nizen.com.br/checkout/:path*",
},
],
};
},
};
Both the source and destination must point to the same sub-path (/checkout) and both fallback blocks are necessary. I'm using Next version 12 by the time I'm writing this.

Configuring a single page Create-React-App on Heroku

With Firebase Hosting, when you deploy an app you are asked whether to rewrite all urls to /index.html. This means react-router routes would be properly fired whether they are accessed directly or navigated to from the homepage.
We use Create-react-app and Create-react-app-buildpack to deploy to Heroku. How can we rewrite all the URLs to /index.html in the same manner?
Following this issue, explaining about the routes directive, I configured a static.json in the root to no avail:
{
"routes": {
"/images/*": "/images/",
"/legal/*": "/images/",
"/media/*": "/media/",
"/fav/*": "/fav/",
"/styles/*": "/styles/",
"/**": "index.html"
}
}
Create a static.json file in the project root with the following content:
{
"root": "build/",
"routes": {
"/**": "index.html"
}
}
More here.

Resources