Using React router V6 and when refresh page I get blank page - reactjs

I am learning ReactJs and I can't understand this problem. I find much discussion about this but it's all for router lower then v6.
On localhost it works OK, but on live server it's not working. If I type this or refresh:
https://greta.portplays.com/app/login
I get a blank white page.
I know this has something to do with history but router v6 doesn't use it the same way as other explanations.
These are my routes, nothing special:
import React from 'react';
import ContentLayout from './components/structure/ContentLayout';
import DashboardLayout from './components/DashboardLayout';
import AccountView from './components/DashboardLayout/views/account/AccountView';
import SearchListView from './components/DashboardLayout/views/search/SearchListView';
import DashboardView from './components/DashboardLayout/views/dashboard/DashboardView';
import NotFoundView from './components/DashboardLayout/views/errors/NotFoundView';
import CreateContentView from './components/DashboardLayout/views/creator/CreateContentView';
import SettingsView from './components/DashboardLayout/views/settings/SettingsView';
import LoginView from './components/DashboardLayout/views/auth/LoginView';
import RegisterView from './components/DashboardLayout/views/auth/RegisterView';
import SubmissionsView from './components/DashboardLayout/views/submissions/SubmissionsView';
import InboxView from './components/DashboardLayout/views/inbox/InboxView';
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <AccountView /> },
{ path: 'search', element: <SearchListView /> },
{ path: 'dashboard', element: <DashboardView /> },
{ path: 'create', element: <CreateContentView /> },
{ path: 'submissions', element: <SubmissionsView /> },
{ path: 'inbox', element: <InboxView /> },
{ path: 'settings', element: <SettingsView /> },
{ path: 'login', element: <LoginView /> },
{ path: 'register', element: <RegisterView /> },
{ path: '*', element: <NotFoundView /> },
{ path: '/', element: <DashboardView /> },
],
},
{
path: '/',
element: <ContentLayout />,
children: [
{ path: '404', element: <NotFoundView /> },
{ path: '*', element: <NotFoundView /> },
],
},
];
export default routes;
In the package.json I added like this
"homepage": "https://greta.portplays.com/",
Also in the Apache server root for the app I added .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>
My app is on a subdomain like this:

Seems to be working fine when local storage is cleared or isUserAnon set to false.

You need to change in package.json file before build.
{
"devDependencies": {},
"homepage": "<Your domain>",
"author": "",
}
run build command again.
npm run build

Related

How to lazy load route with react location?

I am quite new to React, and I have a project that uses react-location
I would like to load some routes lazily only if the path is activated.
My current config is:
my base routing module
export const routes: Route[] = [
...HomeModuleRoutes, // I want this to be instantly loaded.
...LazyRoutes, // I want this to be lazy loaded.
{ path: '/', element: <Navigate to="/home" /> },
];
those 2 constants look like this :
home.routing.ts
export const routes: Route[] = [
{
path: 'home',
element: <HomeTemplate />,
children: [
{
path: '/',
element: <HomePage />,
},
],
},
];
lazy.routing.ts
export const LazyRoutes: Route[] = [
{
path: 'test',
element: <LazyTemplate />,
children: [
{
path: '/',
element: <LazyList />,
},
{
path: 'add',
element: <LazyAdd />,
},
{
path: 'detail',
element: <LazyDetail />,
},
],
},
];
I don't quite see documentation or an example on this, is it just wrapping the component with <Suspense>?
You should import your component with React.lazy like:
const HomeTemplate = React.lazy(() => import("./HomeTemplate "));
check this example for react-router v6 lazy loading

Delete `,` prettier/prettier and Parse errors in imported module './routes'

I download a MUI template for a React web-base app.
In Routes.js file, I commented out a line
and deleted the "," before this line. Later I uncomment the line and add the ",", so it looks the same as before; however, there is an issue as follows: when npm start, it fails to compile.
I'm beginner for reactjs and can't understand what this means.
src\App.js
Line 2:20: Parse errors in imported module './routes': Unexpected token, expected "," (26:8) (26:8) import/no-named-as-default
Line 2:20: Parse errors in imported module './routes': Unexpected token, expected "," (26:8) (26:8) import/no-named-as-default-member
src\routes.js
Line 24:52: Delete `,` prettier/prettier
Line 36:55: Delete `,` prettier/prettier
Search for the keywords to learn more about each error.
routes.js is as follows:
import { Navigate, useRoutes } from 'react-router-dom';
// layouts
import DashboardLayout from './layouts/dashboard';
import LogoOnlyLayout from './layouts/LogoOnlyLayout';
//
import Login from './pages/Login';
import Register from './pages/Register';
import DashboardApp from './pages/DashboardApp';
import Products from './pages/Products';
import Blog from './pages/Blog';
import User from './pages/User';
import NotFound from './pages/Page404';
// ----------------------------------------------------------------------
export default function Router() {
return useRoutes([
{
path: '/dashboard',
element: <DashboardLayout />,
children: [
{ element: <Navigate to="/dashboard/app" replace /> },
{ path: 'app', element: <DashboardApp /> },
{ path: 'user', element: <User /> },
{ path: 'products', element: <Products /> },
// { path: 'blog', element: <Blog /> },
]
},
{
path: '/',
element: <LogoOnlyLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
{ path: '404', element: <NotFound /> },
{ path: '/', element: <Navigate to="/dashboard" /> },
{ path: '*', element: <Navigate to="/404" /> },
]
},
{ path: '*', element: <Navigate to="/404" replace /> }
]);
}
I fixed this question by adding two lines in .eslintrc file
"import/no-named-as-default": 0,
"import/no-named-as-default-member": 0,
that means, I unactive that two rules so no compliling error will be caused by these two rules

React js page reload 404 eror using react-router-dom

Hi i am using react js and react-router-dom for routing.My issue is that when i reload the page i gets below error on browser.my code works fine local server. but on live server i got below error.
Not Found
The requested URL was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
here is my htacess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.html [L]
</IfModule>
here is my routing file
import React from "react";
// Importing Routing Library
import { Navigate } from "react-router-dom";
// Importing Layouts Files
import MainLayout from "src/layouts/MainLayout";
import DashboardLayout from "src/layouts/DashboardLayout";
import ErrorLayout from "src/layouts/ErrorLayout";
// Importing View Files
import NotFoundView from "src/views/errors/NotFoundView";
import LoginView from "src/views/auth/LoginView";
import DashboardView from "src/views/app/DashboardView";
import { AddInstallView } from "src/views/app/Install/AddInstallView";
import { NewInstallView } from "src/views/app/Install/NewInstallView";
import { ExistInstallView } from "src/views/app/Install/ExistInstallView";
import { UpdateInstallView } from "src/views/app/Install/UpdateInstallView";
import { SuccessView } from "src/views/app/Install/SuccessView";
const routes = (loggedIn) => {
//alert(loggedIn);
const routes = [
{
path: "/*",
exact: true,
element: <Navigate to="/auth/login" />,
},
{
path: "/app",
element: loggedIn ? <DashboardLayout /> : <Navigate to="/auth/login" />,
children: [
{ path: "/dashboard", element: <DashboardView /> },
{ path: "/install/add", element: <AddInstallView /> },
{ path: "/install/add/new", element: <NewInstallView /> },
{ path: "/install/list", element: <ExistInstallView /> },
{ path: "/replacement", element: <UpdateInstallView /> },
{ path: "/success", element: <SuccessView /> },
{ path: "/*", element: <Navigate to="/error/404" /> },
],
},
{
path: "/auth",
element: !loggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />,
children: [
{ path: "/login", element: <LoginView /> },
{ path: "/*", element: <Navigate to="/error/404" /> },
],
},
{
path: "/error",
element: <ErrorLayout />,
children: [
{ path: "/404", element: <NotFoundView /> },
{ path: "/*", element: <Navigate to="/error/404" /> },
],
},
];
return routes;
};
export default routes;
What is the solution for this??

React Router can't configure URLs on localhost and remote. Receiving 404 not found error

I've encountered weird situation. I believe that the issue is related to React Router V4 configuration.
I'm using the react-router-modal and React Router v4. With react-router-modal component I render a link to a modal window which have it's own unique URL. Once a link to a modal is clicked - the modal is opened and the URL is added to the address bar. So I could even access the modal window from a new tab with this url:http://localhost:8080/modal_1URL what is very crucial for me.
In dev mode (npm start) everything works fine, also once the invalid URL is entered the page just reloads and invalid URL is remained in address bar. (Not best case)
I thought that everything will work as it is in a production build. But here is a problems. Once the final build is uploaded to the remote server or localhost I get these errors:
1. Once the invalid URL is entered - I receive 404 Not Found
2. Once I try to access a modal with a straight URL (not clicked in loaded page) http://localhost:8080/modal_1 - 404 Not Found
No .htaccess is uploaded
The index.js is very simple and the whole application is onepage with various components:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { ModalContainer } from 'react-router-modal';
import LandingPage from './components/villages/Landing Page.js';
import WOW from 'wowjs';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
class App extends React.Component {
componentDidMount() {
new WOW.WOW().init();
}
render() {
return (
<div>
<LandingPage />
</div>
)
}
}
ReactDOM.render(
<I18nextProvider i18n={i18n}>
<BrowserRouter>
<div>
<App />
<ModalContainer />
</div>
</BrowserRouter>
</I18nextProvider>,
document.getElementById('app')
);
And the component witch renders the modals looks like:
import React from 'react';
import ReactDOM from 'react-dom';
import { ModalRoute, ModalLink } from 'react-router-modal';
import { Link } from 'react-router-dom';
import ImageLoader from 'react-load-image';
function Preloader(props) {
return <img src="img/spinner.gif" className="img-responsive center-block image-loader" />;
}
function ModalOne(props) {
const { t } = props;
return (
<div className='basic__modal-content'>
...
</div>
);
}
const ExtendedModalOne = translate()(ModalOne);
class Items extends React.Component {
render() {
const { t } = this.props;
return (
<div className="container">
<ul>
<div id="works">
<li>
<Link to="/modal_1"> <img src="img/" /> </Link>
<h3>Name</h3>
</li>
</div>
</ul>
<ModalLink component={ExtendedModalOne} path={`/modal_1`} />
<ModalLink component={ExtendedModalTwo} path={`/modal_2`} />
</div>
)
}
}
module.exports = translate()(Items);
and webpack.config:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const staticSourcePath = path.join(__dirname, 'css');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
module.exports = {
stats: {
warnings: false
},
devtool: 'cheap-module-source-map',
devServer: {
historyApiFallback: true,
contentBase: './'
},
entry: {
app: path.resolve(sourcePath, 'index.js')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks (module) {
return module.context && module.context.indexOf('node_modules') >= 0;
}
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'index.html'),
path: buildPath,
excludeChunks: ['base'],
filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new webpack.NoEmitOnErrorsPlugin(),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
},
include: sourcePath
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
Your HTTP server should always send index.html file for any route.
Example NodeJS Express configuration:
// ...
const app = express();
app.get('*', (req, res) => {
res.sendFile('path/to/your/index.html')
})
// ...
As I know, for the Apache server you can use:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
It tells to Apache server to rewrite everything to the index.html page file and let the client handle routing.

nested url routing using react-router and webpack dev server

I'm having some issues working with react-router and webpack-dev-server to achieve nested url routing.
webpack.config.js
output: {
path: path.resolve(__dirname, 'build'),
publicPath: "/", <-- this enabled routing to /register/step2
filename: "js/bundle.js",
},
routes.js
const routes = {
childRoutes: [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{ path: '/register', component: Register },
{ path: '/register/step2', component: SecondStep },
]
};
export default (<Router routes={routes} history={createBrowserHistory()} />);
When clicking around in the appliation, I can get to /register/step2 but once I hit refresh in the browser, my common.js and bundle.js is missing: 404, since it's trying to load everything from /register/ directory.
Can anyone help? Thanks.
I figured it out. 2 things that is needed to enable this.
webpack.config.js
devServer: {
historyApiFallback: true <-- this needs to be set to true
}
routes.js
const routes = {
childRoutes: [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{ path: '/register', component: Register, childRoutes: [
{ path: 'step2', component: SecondStep },
] },
]
};
Make sure your webpack configuration file contains following code:
output: {
publicPath: '/'
},
devServer: {
historyApiFallback: true
}
See more in this article
If you use hashHistory instead of createBrowserHistory() it will keep the server from requesting to your current url on your server.
export default (<Router routes={routes} history={hashHistory} />);

Resources