React router not working on live production - javascript

I have built a UI amazon-clone with create-react-app
it only shows dummy data.
the problem is after publishing it to Vercel, the routing not working as expected! after clicking the links you see a blank page "URL params are correct", you have to manually reload the page to work!
also if you clicked a button no event trigger and you get a blank page!
I wrapped all my routes to MainRoute Component:
const MainRoute = withRouter(({ location }) => {
return (
<>
{location.pathname !== "/login" && location.pathname !== "/signup" ? (
<Header />
) : null}
<Switch>
<Route exact path="/" render={() => <Home />} />
<Route exact path="/products" render={() => <Products />} />
<Route
exact
path="/products/:productID"
render={() => <ProductPage />}
/>
<Route path="/checkout" render={() => <Checkout />} />
<Route path="/payment" render={() => <Payment />} />
<Route path="/login" render={() => <Login />} />
<Route path="/signup" render={() => <Signup />} />
<Route render={() => <NotFoundPage />} />
</Switch>
{location.pathname !== "/login" && location.pathname !== "/signup" ? (
<Footer />
) : null}
</>
);
});
export default withRouter(MainRoute);
my App Component:
function App() {
return (
<div className="app_wrapper">
<Router>
<MainRoute />
</Router>
</div>
);
}
export default App;
repo
https://github.com/aseelban/amazon-clone-app
link:
https://amazon-clone-app-llyl1tfcn.vercel.app/

it works correctly (under Brave browser) the authentication routes, could you please specify which route the issue occurs.!

Thanks, everyone for the help.
I solved this problem by removing HOC withStyles and instead use react-jss.

Related

React Router V6 nested Routes with i18n

I have a question about React Router V6 nested with i18n.
This is my first multi-language service.
const MainPage:React.FC = () => {
const lang = i18n.language;
return (
<>
<Wrapper>
<Routes>
{/* Main */}
<Route path={`/`} element={<Home />}>
<Route path={`${lang}`}>
<Route path={`service`}>
<Route path={'slack'} element={<Slack />} />
</Route>
</Route>
{/* <Route path={`service/dooray`}element={<Dooray />} /> */}
{/* <Route path={`contact`} element={<Contact />} /> */}
{/* <Route path={`app/sign-in`} element={<SignIn />} /> */}
{/* <Route path={`app/sign-up`} element={<SignUp />} /> */}
{/* <Route path={`app/mail-code`} element={<MailCode />} /> */}
{/* <Route path={`app/password/reset`} element={<PwdReset />} /> */}
{/* <Route path={`policies/privac`} element={<Privacy />} /> */}
{/* <Route path={`policies/terms`} element={<Terms />} /> */}
</Route>
{/* <Route path={`*`} element={<>NOT FOUND</>} /> */}
{/* test */}
</Routes>
</Wrapper>
<ParentModal />
</>
If I enter localhost:3000/en, there is an error 'This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.'
How can I fix it..
I want /en => go to english page, /jp => go to japanese page
const MainPage:React.FC =() => {
...
<Route path={`/`} element={<Home />}>
<Route path={`/${lang}/*`}>
<Route path={`service`}>
<Route path="slack" element={<Slack />} />
</Route>
</Route>
</Route>
}
const Home:React.FC = () => {
return (
<>
... UI, JSX
<Outlet />
</>
)
}
I add a <Outlet />. But if I entered '/ko/service/slack', render <Home /> now
<Route path={`/`} element={<Home />}>
<Route path="service">
<Route path="slack" element={<Slack />} />
<Route path="dooray" element={<Dooray />} />
</Route>
</Route>
nested-routes doesn't work.. :(
I had the exact same useCase (localize react router v6) and came up with the following LangRouter repository link:
const LangRouter = () => {
const { i18n } = useTranslation(),
{ pathname, search, hash } = useLocation(),
navigate = useNavigate(),
availableLocales = ['en', 'ar'],
defaultLocale = (
getDefaultLanguage() === 'en' || getDefaultLanguage() === 'ar' ? getDefaultLanguage() : 'en'
) as string,
pathnameLocale = pathname.substring(1, 3).toLowerCase(),
[locale, setLocale] = useState(defaultLocale),
loaderTimerRef = useRef<any>(),
[isLoading, setIsLoading] = useState(true);
useEffect(() => {
loaderTimerRef.current = setTimeout(() => {
setIsLoading(false);
clearTimeout(loaderTimerRef.current);
}, 300);
}, []);
useEffect(() => {
if (availableLocales.includes(pathnameLocale)) {
updateLocale(pathnameLocale);
} else if (pathname === '/') {
updateLocale(defaultLocale);
}
// eslint-disable-next-line
}, [pathname]);
useEffect(() => {
let lang = defaultLocale;
if (availableLocales.includes(pathnameLocale)) {
lang = pathnameLocale;
setLanguageHandler(lang);
} else if (pathname === '/') {
setLanguageHandler(lang);
}
// eslint-disable-next-line
}, [locale]);
const setLanguageHandler = (lang: string) => {
if (lang === 'en') {
i18n.changeLanguage('en-US');
} else {
i18n.changeLanguage('ar-SA');
}
};
const updateLocale = (newLocale: string) => {
const newPath = `/${newLocale}` + pathname.substring(3);
if (locale !== newLocale) {
if (newPath === `/${newLocale}/` || newPath === `/${newLocale}` || pathname === '/') {
navigate(getHomePageUrl(newLocale));
} else {
navigate(`${newPath}${hash}${search}`);
}
setLocale(newLocale);
} else if (newPath === `/${newLocale}/` || newPath === `/${newLocale}` || pathname === '/') {
if (isAuthenticated()) {
navigate(getHomePageUrl(newLocale));
} else {
navigate(getLoginPageUrl(newLocale));
}
}
};
if (isLoading) {
return (
<div className="loader-wrapper">
<LoadingIcon />
</div>
);
}
return (
<LocaleContext.Provider value={{ locale, setLocale: updateLocale }}>
<Routes>
<Route path={`/${locale}`} element={<App />}>
{publicRoutes.map((el, i) => (
<Route
key={i}
path={el.path(locale)}
element={
<PublicRouteGuard
restricted={el.restricted}
redirect={el.redirect ? el.redirect(locale) : undefined}
>
{el.element}
</PublicRouteGuard>
}
/>
))}
{privateRoutes.map((el, i) => (
<Route
key={i}
path={el.path(locale)}
element={
el.permissions ? (
<RestrictedRouteGuard requiredPermissions={el.permissions}>
{el.element}
</RestrictedRouteGuard>
) : (
<PrivateRouteGuard>{el.element}</PrivateRouteGuard>
)
}
>
{el.children &&
el.children.map((innerEl, innerI) => (
<Route key={innerI} path={innerEl.path(locale)} element={innerEl.element} />
))}
</Route>
))}
</Route>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</LocaleContext.Provider>
);
};
export default LangRouter;
Issue
The error 'This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.' means the parent route isn't rendering an Outlet component for the nested routes to be rendered into. The route rendering the Home component doesn't appear to be rendering an Outlet.
Solution
Update the Home component to render an Outlet. Note that Route components without an element prop will render an Outlet by default.
Example:
import { Outlet } from 'react-router-dom';
const Home = () => {
...
return (
<>
... home page UI/JSX ...
<Outlet />
</>
);
};
...
const MainPage:React.FC = () => {
const lang = i18n.language;
return (
<>
<Wrapper>
<Routes>
{/* Main */}
<Route path="/" element={<Home />}>
<Route path={lang}> // <-- renders Outlet by default
<Route path="service"> // <-- renders Outlet by default
<Route path="slack" element={<Slack />} />
</Route>
</Route>
...
</Route>
...
{/* test */}
</Routes>
</Wrapper>
<ParentModal />
</>
);
};
Update
If the Home and Slack components are separate and independent, then move the Home component into an index route and simplify the routing to the Slack component.
<Routes>
<Route path="/">
<Route index element={<Home />} />
<Route path={`${lang}/service/slack`} element={<Slack />} />
</Route>
</Routes>

How to redirect user to a diferent path if token is expired

I'm making a simple site for a project, and i want to redirect player to a login page if the token is expired, but I'm not really sure how to do it properly, here's what I've tried, im using react-jwt to check the token
function App() {
return (
<div style={{display:'flex', flexDirection:'column', height:'100vh'}}>
<Navbar/>
<div style={{display:'flex', flex:1}}>
<Routes>
<Route path="/login" element ={<LoginForm/>} />
<Route path="/signUp" element ={<SignUpForm/>} />
<Route path="/addMovie" element= {<AddMovie/>} />
<Route path="/" element={isExpired(localStorage.getItem('token') ? <FilmList/> : <LoginForm/> )} />
<Route path="/details" exact element ={<MovieDetails/>} />
</Routes>
</div>
</div>
);
}
or something like
<Route path="/"
render={props=>{
if(isExpired(localStorage.getItem('token'))){
return <Navigate to='/login'/>;
}
return <FilmList/>
}}
/>
The first one just returns nothing, and the second one gives a warning in console:
Matched leaf route at location "/" does not have an element. This
means it will render an with a null value by default resulting in an
"empty" page.
Is there a way to make it work ?
In react-router-dom v6 gone are custom route components, and the Route component must have a valid ReactElement on the element prop. A function is incorrect. Your second snippet is close.
Create an AuthWrapper to conditionally render an Outlet for a nested route or a redirect.
const AuthWrapper = () => {
return isExpired(localStorage.getItem('token')
? <Navigate to="/login" replace />
: <Outlet />;
};
Wrap any routes you want to protect into a Route rendering the AuthWrapper.
function App() {
return (
<div style={{display:'flex', flexDirection:'column', height:'100vh'}}>
<Navbar />
<div style={{display:'flex', flex:1}}>
<Routes>
<Route path="/login" element={<LoginForm />} />
<Route path="/signUp" element={<SignUpForm />} />
<Route path="/addMovie" element={<AddMovie />} />
<Route element={<AuthWrapper />}>
<Route path="/" element={<FilmList />} />
</Route>
<Route path="/details" element={<MovieDetails />} />
</Routes>
</div>
</div>
);
}
One solution would be to use the Redirect component from react-router-dom.
Fo into your FilmList component and in the rendering part do the following check:
if (isExpired(localStorage.getItem('token')){
return <Redirect to='/login' />
}
before you return your 'normal' FilmList
FOR RRDv6 that doesn't support Redirect you can use the Navigate component:
if (isExpired(localStorage.getItem('token')){
return <Navigate to='/login' replace={true} />
}

Bind slug like the first URL segment

I'm developing react app use react-router-dom. I have unusual the app behavior. The app doesn't have home page. We can go to the app use 'slug'. For example: http://siteExample.net/my-subsite. If my-subsite exist in our database We need to work with this slug.
My code snippet for routes:
const App = ({ isAuth, onSetSlug, slug}) => {
useEffect(() => {
onSetSlug(window.location.pathname.split('/')[1])
}, [])
return (
<Router>
<div className="App">
<Suspense fallback={<Loading />}>
<MainModal />
<ScrollToTop>
{!isAuth ? (
<Switch>
<Route path={'/:slug'} exact component={lazy(() => import('./containers/notAuth/home'))} />
<ContentWrapper
container
component="main"
adaptSidebar={5}
adaptContent={7}
>
<Switch>
<Route path={'/:slug/login'} exact component={lazy( () => import('./containers/notAuth/login'))} />
<Route path={'/:slug/signup'} exact component={lazy(() => import('./containers/notAuth/signup'))} />
<Redirect to={'/:slug'} />
</Switch>
</ContentWrapper>
<Redirect to={'/:slug'} />
</Switch>
</ScrollToTop>
</Suspense>
</div>
</Router>
)}
There is a issue that :slug/login doesn't replace on my-subsite/login for example.By the way it's working only for my local machine. When I publish it to remote host it doesn't work completely.
Remove the exact prop on the outer/root route since it necessarily excludes matching any subroutes.
<Switch>
<Route
path={'/:slug'} // <-- want this path prefix to match
component={lazy(() => import('./containers/notAuth/home'))}
/>
<ContentWrapper
container
component="main"
adaptSidebar={5}
adaptContent={7}
>
<Switch>
<Route
path={'/:slug/login'}
exact
component={lazy( () => import('./containers/notAuth/login'))}
/>
<Route
path={'/:slug/signup'}
exact
component={lazy(() => import('./containers/notAuth/signup'))}
/>
<Redirect to={'/:slug'} />
</Switch>
</ContentWrapper>
<Redirect to={'/:slug'} />
</Switch>

using Multiple header in react router

class App extends Component {
render() {
let pathName=window.location.pathname;
console.log('pathName==>',pathName);
let loginhideheaderpath = pathName==="/" || pathName==="/login";
let securnetheaderpath = pathName==='/Contentlanding/Reports';
let gallerypath = pathName==='/Contentlanding/Gallerylanding'
return (
<>
{ securnetheaderpath ? <Securnetheader /> : ( loginhideheaderpath) ? null :(gallerypath) ? <Galleryheading /> : <Header /> }
<Router history={history}>
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/login" component={Login} />
<Route exact path="/Contentlanding" component={Contentlanding} />
<Route exact path="/Contentlanding/Birthdaylist" component={Birthdaylist} />
<Route exact path="/Contentlanding/Reports" component={Reports} />
<Route exact path="/Contentlanding/Gallerylanding" component={Gallerylanding} />
<Route component={Nodocumentfound} />
</Switch>
</Router>
</>
);
}
}
In my project i am using mutiple headers, i am rendering the header for components based on URL.
my condition is working fine. the problem is when i use the browser back button the header are not changing. any solution to fix this Thanks in advance.

If condition to change route using React Router V4

I have two types of routes, countries and content:
/countries
/industry/ranking
/industry/audience
/website/ranking
/website/audience
/website/conversion
etc...
When the user enters the application, I have to verify if he already chose a country, which I'm saving using localStorage.
If the user has the country already chosen, he needs to go to /industry/ranking, if don't, to /countries.
I'm receiving a warning about the route changing by code:
<Route> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.
My code:
<Switch>
<Route exact path='/countries' component={Countries} />
{
current && (
<React.Fragment>
<Route exact path='/industry/ranking' render={() => <IndustryRanking country={current} />} />
<Route path='/industry/audience' render={() => <IndustryAudience country={current} />} />
<Route path='/website/ranking' render={() => <WebsiteRanking country={current} />} />
<Route path='/website/audience' render={() => <WebsiteAudience country={current} />} />
<Route path='/website/device' render={() => <WebsiteDevice country={current} />} />
<Route path='/website/conversion-orders' render={() => <WebsiteConversionOrders country={current} />} />
</React.Fragment>
)
}
{ !current ? <Redirect to='/countries' /> : <Redirect to='/industry/ranking' /> }
</Switch>
Is there a way to improve this using just the routes to verify my condition?
Thanks!
You can simply write a custom component that renders the Routes or redirects to the country instead of conditionally rendering the Routes which is causing this warning
const CustomRoute = (props) => {
const current = localStorage.getItem('country');
if(current) {
return <Route {...props} />
}
return <Redirect to='/countries' />
}
and use it like
<Switch>
<CustomRoute exact path='/countries' component={Countries} />
<CustomRoute exact path='/industry/ranking' render={() => <IndustryRanking country={current} />} />
<CustomRoute path='/industry/audience' render={() => <IndustryAudience country={current} />} />
<CustomRoute path='/website/ranking' render={() => <WebsiteRanking country={current} />} />
<CustomRoute path='/website/audience' render={() => <WebsiteAudience country={current} />} />
<CustomRoute path='/website/device' render={() => <WebsiteDevice country={current} />} />
<CustomRoute path='/website/conversion-orders' render={() => <WebsiteConversionOrders country={current} />} />
<Redirect to='/industry/ranking' />
</Switch>

Categories

Resources