Issues in making Routes in Reactjs - javascript

I am making a project and getting some problem in managing routes. My Frontend is divided in two parts. One For the Client side and onother is the admin-panel for handling the Client side. For example if I add some Blog from admin-panel then it shows on Client-side. Admin-Panel is for my team to handle the website. Suppose Users will visit on my website at "www.mywebsite.com' and I want that if I enter "www.mywebsite.com/admin" then Admin-panel and Admin-components should open instead of Nav-Components.
How Do I achieve this conditional routing?
Here is the App.js
import React, { Component, useEffect, useState } from "react";
import { Route, Switch } from "react-router-dom";
import Landing from "./components/Landing";
import Home from "./components/Home";
import About from "./components/About";
import Teams from "./components/Team";
import Events from "./components/Events";
import NotFound from "./components/NotFound";
import Blog from "./components/Blog";
import ContactUs from "./components/Contact";
import ComingSoon from "./components/ComingSoon";
import Navbar from "./components/Navbar";
import EventInfo from "./components/EventInfo";
import AdminNavbar from "./admin-panel/AdmiNavbar";
import Login from "./admin-panel/Login";
import Eventadd from "./admin-panel/Eventadd";
import Blogadd from "./admin-panel/Blogadd";
import Dashboard from "./admin-panel/Dashboard";
const NavComponents = () => {
return (
<>
<Switch>
<Route path="/home" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/events" exact component={Events} />
<Route path="/team" exact component={Teams} />
<Route path="/blog" exact component={Blog} />
<Route path="/contact" exact component={ContactUs} />
<Route path="/comingsoon" exact component={ComingSoon} />
<Route path="/eventinfo/:eventName" exact component={EventInfo} />
<Route component={NotFound} />
</Switch>
</>
);
};
const AdminPanel = () =>{
return(
<>
<Switch>
<Route path="/admin/Eventadd" exact component={Eventadd}/>
<Route path="/admin/Blogadd" exact component={Blogadd}/>
<Route path="/admin/DashBoard" exact component={Dashboard}/>
<Route component={NotFound} />
</Switch>
</>
);
};
class App extends Component {
render() {
return (
<>
{window.location.pathname=="/"?"": <Navbar />}
<Switch>
<Route path="/" exact component={Landing} />
<NavComponents />
</Switch>
</>
);
}
}
export default App;

I assume if users enter your website through "www.mywebsite.com/admin" link, you want to re-route them to "/admin/DashBoard" route? The admin dashboard doesn't show because, it only returns the route with EXACT match. It's possible to
A) Add an additional path to handle the routing
<Route path=["/admin/DashBoard", "/admin"] exact component={Dashboard}/>
B) Add a Redirect for admin if you prefer to keep the route as /admin/dashboard
<Redirect exact from="/admin" to={`/admin/dashboard`} />
Edit: (Most importantly)
Also, noticed that you did not include the admin into the main router. You don't need to separate the admin from nav. Suggest to read on the document
https://reactrouter.com/web/api/Switch
Switch renders the first child <Route> or <Redirect> that matches the location.
Overall, it should be combined like this
<Switch>
...user paths
...admin paths
</Switch>

Related

React Router v6 always render "/"

I'm trying to implement router in react-create-app but it always render "/" and showing Home or SignIn page. How can I solve this?
function AppRouter({ isLoggedIn, user }) {
return(
<Router>
<Routes>
<Route path="/profile" element={<Profile />} />
<Route path="/signUp" element={<SignUp />} />
{isLoggedIn
? <Route exact path={"/"} element={<Home user={user}/>} />
: <Route exact path={"/"} element={<SignIn />} />
}
</Routes>
</Router>
)
}
It seems you have a slight misunderstanding of how the HashRouter works with the UI.
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Profile from "./Profile";
import SignUp from "./SignUp";
import Home from "./Home";
export default function App() {
return (
<Router>
<Routes>
<Route path="/profile" element={<Profile />} />
<Route path="/signUp" element={<SignUp />} />
<Route path="/" element={<Home />} />
</Routes>
</Router>
);
}
The HashRouter handles routing with a URL hash value, i.e. everything after the "#" in the URL. If you are trying to render your app and access "<domain>/" instead of "<domain>/#/" the routing won't work.
For example in your running codesandbox demo, the base URL is "https://5p7hff.csb.app/". At this base URL the hash router isn't really working, and you should really be accessing "https://5p7hff.csb.app/#/" instead so the hash router is loaded and the app's internal routing can work.
From "https://5p7hff.csb.app/#/" you should be to then navigate to any of your routes, i.e. "https://5p7hff.csb.app/#/profile" and https://5p7hff.csb.app/#/signUp".
If you switch to a different router, like the BrowserRouter then the "/#/" is no longer used, the router and routes render from "/" where the app is running from. The routes would be "https://5p7hff.csb.app/", "https://5p7hff.csb.app/profile", and "https://5p7hff.csb.app/signUp".

Why my components don't display on my React page?

So I'm learning React and building an app with multiple pages, I made a Routes file which looks like this:
import 'swiper/swiper.min.css';
import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import Catalog from "../pages/Catalog";
import Detail from "../pages/Detail";
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
component={Catalog}
/>
<Route
path='/:category/:id'
component={Detail}
/>
<Route
path='/:category'
component={Catalog}
/>
<Route
path='/'
exact
component={Home}
/>
</Routes>
);
}
And App.js looks like this:
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Header from './components/header/Header';
import Footer from './components/footer/Footer';
import Router from './config/Router';
function App() {
return (
<BrowserRouter>
<Routes>
<Route render={props =>{
<>
<Header {...props}/>
<Router/>
<Footer/>
</>
}}/>
</Routes>
</BrowserRouter>
);
}
export default App;
As you see, I have a browser router and Route which passes props to a component(as I understood) but for some reason the components don't display on the page(original components just have with their name inside of them, but they don't display in App.js).
And my console also says:
No routes matched location "/"
In routes.jsx file. I'm guessing it should lead to main page, but for some reason the route doesn't match and components in App.js don't display.
In Version 6.0.0 there is not any component prop in Route. It has been changed to element. So you need to change your Router to :
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
element={Catalog}
/>
<Route
path='/:category/:id'
element={Detail}
/>
<Route
path='/:category'
element={Catalog}
/>
<Route
path='/'
exact
element={Home}
/>
</Routes>
);
}
As you've said you're using react-router-dom 6.0.2, and it seems that the tutorial you are following is for the older version (5?). There were some breaking changes in version 6.
You need to change your Router component to use element instead of component:
const Router = () => {
return (
<Routes>
<Route path="/:category/search/:keyword" element={<Catalog />} />
<Route path="/:category/:id" element={<Detail />} />
<Route path="/:category" element={<Catalog />} />
<Route path="/" exact element={<Home />} />
</Routes>
);
};
and also your App component seems to be getting in the way with the nested route.
I think it can be simplified to:
function App() {
return (
<BrowserRouter>
<>
<Header />
<Router />
<Footer />
</>
</BrowserRouter>
);
}
You can see a working demo on stackblitz

Error 404 while targeting url in React.js

For example if I open this link https://cubeacloud.com/ , it will open easily
but if I target this specific link https://cubeacloud.com/contact
it will show me error 404 (open 2nd link in private tab)
I tried all the the things in routing
Routing code is given below
import react from 'react';
import { Switch, Route, Router, BrowserRouterProps } from 'react-router-dom';
import LandingPage from './landingpage';
import AboutMe from './aboutme';
import Contact from './contact';
//projects
import Projects from './projects/projects';
import Graphics from './projects/graphics';
import Content from './projects/contant';
import Nav from '../navbar';
// import Resume from './resume';
//blogs
import Blogs from './blogs/blog';
import CryptoBlogs from './blogs/crypto';
import GamesBlogs from './blogs/games';
import ItBlogs from './blogs/it'
import EducationBlogs from './blogs//education'
//education
import Education from './education/education';
import Books from './education/books';
import Videos from './education/videos';
import Quiz from './education/quiz'
import Courses from './education/courses'
const Main = () => (
<Switch>
<Route exact path={process.env.PUBLIC_URL + '/'} component={LandingPage} />
<Route path="/aboutme" component={AboutMe} />
<Route path="/contact" component={Contact} />
{/* All Projects */}
<Route path="/projects/projects" component={Projects} />
<Route path="/projects/graphics" component={Graphics} />
<Route path="/projects/content" component={Content} />
{/* <Route path="/blog" component={Blogs} /> */}
{/* All Education */}
<Route path="/education/education" component={Education} />
<Route path="/education/books" component={Books} />
<Route path="/education/videos" component={Videos} />
<Route path="/education/courses" component={Courses} />
<Route path="/education/quiz" component={Quiz} />
{/* All Blogs */}
<Route path="/blogs/blog" component={Blogs} />
<Route path="/blogs/crypto" component={CryptoBlogs} />
<Route path="/blogs/education" component={EducationBlogs} />
<Route path="/blogs/it" component={ItBlogs} />
<Route path="/blogs/games" component={GamesBlogs} />
</Switch>
)
export default Main;
enter image description here
Failed to load resource: the server responded with a status of 404 ()
WEB IS WORKING FINE ON LOCALHOST & LOCAL NETWORK,
You have done right, also you have structured you Main React functional component very well, here only one thing you have to use BrowserRouter.
Please, wrap your <Switch>...</Switch> with <BrowserRouter></BrowserRouter/>
import { BrowserRouter } from 'react-router-dom';
const Main = () => (
<BrowserRouter>
<Switch>
//your custom routes
<Route> // not found route(404)
<p>Not Found</p>
</Route>
</Switch>
</BrowserRouter>
);
export default Main;

Components After React Suspense Not Loading?

I had to break up some of my routes with suspense and react.lazy to ensure that my bundle file wasn't ridiculous. But after doing so, the routes after my first suspense bracket are no longer working?
In the following example, the routes for Links 1 - 6 are working properly (no issue and they render properly). But the components inside the Suspense and all the ones after it (inside and outside the suspense) aren't loading properly. You go to that route and nothing loads on the page. Even the Spinner component doesn't load as the fallback. I've tried removing the spinner component as the fallback and just doing Loading... and even that won't appear on the page.
My import statements:
import React, { Component } from 'react';
import { Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
My component import structure example:
import Comp1 from './components/Comp1';
import Comp2 from './components/Comp2';
import Comp3 from './components/Comp3';
import Comp4 from './components/Comp4';
import Comp5 from './components/Comp5';
import Comp6 from './components/Comp6';
import Comp9 from './components/Comp9';
const Comp7 = React.lazy(() => import('./components/Comp7'));
const Comp8 = React.lazy(() => import('./components/Comp8'));
const Comp10 = React.lazy(() => import('./components/Comp10'));
(Example of my route tree)
<Route exact path="/link-1" component={ Comp1 } />
<Route exact path="/link-2" component={ Comp2 } />
<Route exact path="/link-3" component={ Comp3 } />
<Route exact path="/link-4" component={ Comp4 } />
<Route exact path="/link-5" component={ Comp5 } />
<Route exact path="/link-6" component={ Comp6 } />
<Suspense fallback={<Spinner /> }>
<Route exact path="/link-7" component={ Comp7 } />
<Route exact path="/link-8" component={ Comp8 } />
</Suspense>
<Route exact path="/link-9" component={ Comp9 } />
<Suspense fallback={<Spinner /> }>
<Route exact path="/link-10" component={ Comp10 } />
</Suspense>
<Route exact path="/link-11" component={ Comp11 } />
Edit: Showcasing the way I fixed it.
<Suspense fallback={<Spinner /> }>
<Route exact path="/link-1" component={ Comp1 } />
<Route exact path="/link-2" component={ Comp2 } />
<Route exact path="/link-3" component={ Comp3 } />
<Route exact path="/link-4" component={ Comp4 } />
<Route exact path="/link-5" component={ Comp5 } />
<Route exact path="/link-6" component={ Comp6 } />
<Route exact path="/link-7" component={ Comp7 } />
<Route exact path="/link-8" component={ Comp8 } />
<Route exact path="/link-9" component={ Comp9 } />
<Route exact path="/link-10" component={ Comp10 } />
</Suspense>
It had to do with my React-Router. The documentation and sources I was reviewing for it said that the routes could be in the normal route tree, turned out that wasn't the case. Suspense had to be outside the Statement for react-router. After wrapping every route outside the switch statement, it worked properly.

React Router v5 nested routes not found

I'm having problems trying to make a simple setup to run. I have used "react-router-dom" because it claims to be the most documented router around.
Unfortunately, the documentation samples are using functions instead of classes and I think a running sample will not explain how routes have changed from previous versions... you need a good sight!. Btw, there are a lot of breaking changes between versions.
I want the following component structure:
Home
Login
Register
Recipes
Ingredients
Have the following components:
index.js (works fine)
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
ReactDOM.render((
<BrowserRouter>
<Route component={App}/>
</BrowserRouter>
), document.getElementById('root'));
App.js (fine)
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './Home'
import Recipes from './recipes/Recipes'
import Ingredients from './ingredients/Ingredients'
class App extends React.Component {
render() {
return (
<div id="App">
<Switch>
<Route exact path='/home' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
</div>
);
}
}
export default YanuqApp;
Ingredients and Recipes components working fine, so I'll skip from here
Home.js - The problem starts here. Home itself loads correctly, but once Login or Register links are clicked, it shows "Not found!" (fallback route in App.js)
import React from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import Register from './account/register'
import Login from './account/login'
class Home extends React.Component {
render() {
return (
<div>
<div>
This is the home page...<br/>
<Link to='/home/login'>Login</Link><br />
<Link to='/home/register'>Register</Link><br />
</div>
<Switch>
<Route path='/home/login' component={Login} />
<Route path='/home/register' component={Register} />
</Switch>
</div>
);
}
}
export default Home;
Login and register are very similar:
import React from 'react';
class Login extends React.Component {
render() {
alert("login");
return (
<div>Login goes here...</div>
);
}
}
export default Login;
And cannot figure why Login and Register are not found. I have tried also defining routes as:
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
(don't see the gain on using match, as it renders as the expected "/home/register"), but the problem persists in identical way
I think it's because of the exact flag on the Route for home. It does not match the /home exact so it goes to the default not found page.
try to add this in App.js
<Switch>
<Route exact path='/' component={Home} />
<Route path='/recipes' component={Recipes} />
<Route path='/ingredients' component={Ingredients} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<Route render={() => <h1>Not found!</h1>} />
</Switch>
to this is work
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
you should provide match as the props because cont access directly to the match to used it you should provide a match as this following
const namepage=({match})=>{
<Link to={`${match.path}/register`}>Register</Link>
...
<Route path={`${match.path}/register`} component={Register} />
})

Categories

Resources