React Router: Component not getting displayed - javascript

I have just started with React and not able to get the router working. Below is the code for router. If I use the individual components without the router, they are displayed on the screen. But with router I don't get any text on the screen across any of the paths.
Please let me know if I am missing something. Below is the code:
import { Route } from 'react-router-dom';
import AllMeetupsPage from './pages/AllMeetups';
import NewMeetupPage from './pages/NewMeetup';
function App() {
return (
<div>
<Route path='/' exact>
<AllMeetupsPage />
</Route>
<Route path='/new-meetup'>
<NewMeetupPage />
</Route>
</div>);
}
export default App;

A route needs to be a descendent of router component. I'm not sure which version of react-router you're using, but this will be a BrowserRouter and Routes component for react-router v6 and on v4/v5 it'll be a BrowserRouter
Here's some examples:
v6:
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import AllMeetupsPage from './pages/AllMeetups';
import NewMeetupPage from './pages/NewMeetup';
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" exact element={<AllMeetupsPage />}/>
<Route path="/new-meetup" element={<NewMeetupPage />}/>
</Routes>
</BrowserRouter>
</div>);
}
export default App;

You missed using Switch component
import { Route , Switch } from 'react-router-dom';
function App() {
return (
<div>
<Switch>
<Route path='/' exact>
<AllMeetupsPage />
</Route>
<Route path='/new-meetup'>
<NewMeetupPage />
</Route>
</Switch>
</div>);
}
export default App;

Related

404 page appear in every page anytime in react js

app.js
import { BrowserRouter as Switch, Route } from "react-router-dom";
import Login from "./Pages/Login";
import ViewPurchaseOrders from "./Pages/purchases/ViewPurchaseOrders";
import ViewProductSelectionGrn from "./Pages/GRN Management/View.product.selection-grn";
import Error from "./Components/404page/Error";
function App() {
return (
<div>
<Switch>
<Route path="/" exact component={Login} />
<ProtectedRoute
exact
path="/confirm-purchase-orders"
component={ViewPurchaseOrders}
/>
<ProtectedRoute
exact
path="/grn-product-selections"
component={ViewProductSelectionGrn}
/>
<Route path="*">{Error}</Route>
</Switch>
</div>
);
}
export default App;
404 page is rendering everywhere like above attached picture. I need to fix it. I tried few ways but it doesn't work properly.
Issue
The issue here is that you've managed to import the BrowserRouter as a Switch, so the Switch is really just a plain old router and all routes are being inclusively matched and rendered, i.e. all matching routes are rendered. Routes rendering on path="*" will always be matched and rendered.
import {
BrowserRouter as Switch, // <-- whoopsies!
Route
} from "react-router-dom";
...
function App() {
return (
<div>
<Switch> // <-- BrowserRouter in disguise
<Route path="/" exact component={Login} />
<ProtectedRoute
exact
path="/confirm-purchase-orders"
component={ViewPurchaseOrders}
/>
<ProtectedRoute
exact
path="/grn-product-selections"
component={ViewProductSelectionGrn}
/>
<Route path="*">{Error}</Route> // <-- always rendered
</Switch>
</div>
);
}
Solution
Import the BrowserRouter as a Router, then import the Switch and continue to render the routes into it so they are exclusively matched and rendered, i.e. only one match.
Example:
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
...
function App() {
return (
<div>
<Router>
<Switch>
<ProtectedRoute
path="/confirm-purchase-orders"
component={ViewPurchaseOrders}
/>
<ProtectedRoute
path="/grn-product-selections"
component={ViewProductSelectionGrn}
/>
<Route path="/" component={Login} />
<Route path="*">{Error}</Route>
</Switch>
</Router>
</div>
);
}

remove # from url react-router-dom in react js

I am new in react.js
I am using react-router-dom v6 and I working on a theme where I find an issue with # in URL
Example:- {url}/#/dashboard
I want
Example:- {url}/dashboard
I think you have to use BrowserRouter instead of HashRouter
1. You can add it in your index.js or index.tsx depending on your project.
import { BrowserRouter } from 'react-router-dom'
root.render(
<BrowserRouter>
<App/>
</BrowserRouter>)
2. You can also add in your App.js or App.tsx depending
import { BrowserRouter,Routes,Route } from 'react-router-dom'
const App = () => {
return (
<BrowserRouter className='main'>
<Routes>
<Route exact path='/' element={<Home />} />
</Routes>
<Routes>
</Routes>
</BrowserRouter>
);
}
am assuming, you are using HashRouter if yes then please use BrowserRouter instead HashRouter
implement BrowserRouter on routing
import { BrowserRouter,Route, Routes } from 'react-router-dom'
render(
<BrowserRouter>
<Routes>....</Routes>
</BrowserRouter>)
You have to use BrowserRouter instead of HashRouter from react-router-dom
In your App.js file, try like below.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import LandingPage from './Containers/LandingPage';
const App = () => {
return (
<BrowserRouter className='App'>
<Routes>
<Route exact path='/' element={<LandingPage />} />
</Routes>
<Routes>
<Route ... ... />
</Routes>
... ...
</BrowserRouter>
);
}
export default App;

react components not rendering with routes

I am using the latest version of react router. When I am using routes in my component, They are not rendering anything but When I remove the routes and use simply the component they are working fine. Not able to understand what is going wrong
This do not work and is not rendering anything on "/" or http://localhost:3000/
import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Route path="/" exact>
<Users />
</Route>
<Navigate to="/" />
</Router>
);
}
export default App;
This is rendering and working fine.
import React from "react";
import { BrowserRouter as Router, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return <Users />;
}
export default App;
import React, {useState} from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
import Profiles from "./Profiles" // this is dummy
function App() {
const [state, setState] = useState(false)
return (
<Router>
<Routes>
<Route path="/" element={<Users />}/>
<Route path="/profiles" element={state ? <Profiles /> : <Navigate to="/" />} />
{/* so you redirect only if your state is false */}
</Routes>
</Router>
);
}
export default App;
It is because, You din't provide which element to render in Route. It has to be mentioned like element={<Users />}. So try like below,
import React from "react";
import { BrowserRouter as Router, Route, Routes, Navigate } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Users />} />
<Navigate to="/" />
</Routes>
</Router>
);
}
export default App;
Based on the docs, all Route components should be placed inside a Routes component, which is nested inside the BrowserRouter.
Also, I noticed you use Navigate everytime, even when you are already at the index path. I think this may cause a problem...
So, with that in mind, Change your code to
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Users from "./user/pages/Users";
function App() {
return (
<Router>
<Routes>
<Route path="/">
<Route index element={<Users />} />
</Route>
</Routes>
</Router>
);
}
export default App;
Issue
In react-router-dom#6 the Route component renders its content on the element prop as a ReactNode, a.k.a. JSX, the only valid child of the Route component is another Route component for the case of nesting routes. The Users component should be moved to the element prop.
Also, to render a redirect to a default route, the Navigate component should also be rendered on a generic route.
Solution
Move Users component onto route's element prop.
Move the Navigate component into a generic route and pass the replace prop so issue a redirect.
Example:
function App() {
return (
<Router>
<Route path="/" element={<Users />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Router>
);
}

Re-use navbar component with multiple components

I have a simple question. What is the best way to use a navbar with multiple components using react router? Just let me show the code so you can understand what I'm trying to say.
import React from "react";
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
import Auth from "./website/Auth/Auth";
import SocialMedia from "./website/SocialMedia/SocialMedia";
import SingleUser from "./website/SingleUser/SingleUser";
import Search from "./website/Search/Search";
import SinglePhoto from "./website/SinglePhoto/SinglePhoto";
import Navbar from "./components/Navbar/Navbar";
function App() {
const logIn = JSON.parse(localStorage.getItem("token"));
return (
<Router>
<Switch>
<Route exact path="/" component={Auth}>
{logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
</Route>
<Navbar>
<Route exact path="/profile/:id" component={SingleUser} />
<Route exact path="/socialmedia" component={SocialMedia} />
<Route exact path="socialmedia/search" component={Search} />
<Route exact path="socialmedia/photo/:id" component={SinglePhoto} />
</Navbar>
</Switch>
</Router>
);
}
export default App;
So I have to reuse my Navbar component, and I tried to use <Navbar />, then the other routes below, but that wasn't working, and when I put <Navbar> </Navbar> that worked and the other components will appear, but is that the way I reuse my Navbar component?
Thanks for your time !!
import React from "react";
import "./App.css";
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
import Auth from "./website/Auth/Auth";
import SocialMedia from "./website/SocialMedia/SocialMedia";
import SingleUser from "./website/SingleUser/SingleUser";
import Search from "./website/Search/Search";
import SinglePhoto from "./website/SinglePhoto/SinglePhoto";
import Navbar from "./components/Navbar/Navbar";
function App() {
const logIn = JSON.parse(localStorage.getItem("token"));
return (
<Router>
<Switch>
<Route exact path="/" component={Auth}>
{logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
</Route>
<Route Component={Navbar}>
<Route exact path="/profile/:id" component={SingleUser} />
<Route exact path="/socialmedia" component={SocialMedia} />
<Route exact path="socialmedia/search" component={Search} />
<Route exact path="socialmedia/photo/:id" component={SinglePhoto} />
</Route>
</Switch>
</Router>
);
}
export default App;
Try this!
If you want the Navbar to render only on certain routes then render it only on certain routes. Render the Navbar into a route outside the Switch and specify all the paths you want it to be rendered on in an array on the path prop.
Additional notes:
Within the Switch component, order and path specificity matter, reorder your routes to specify more specific paths before less specific paths. This allows you to not need to specify the exact prop for every route.
Don't specify both a component prop and render children on a single Route, see Route render methods. Just render the Redirect or Auth component as children.
Code:
function App() {
const logIn = JSON.parse(localStorage.getItem("token"));
return (
<Router>
<Route
path={["/profile", "/socialmedia"]}
component={Navbar}
/>
<Switch>
<Route path="/profile/:id" component={SingleUser} />
<Route path="socialmedia/photo/:id" component={SinglePhoto} />
<Route path="socialmedia/search" component={Search} />
<Route path="/socialmedia" component={SocialMedia} />
<Route path="/">
{logIn ? <Redirect to={`/profile/${logIn.data.id}`} /> : <Auth />}
</Route>
</Switch>
</Router>
);
}

React Router Not Working Like I Need It Too

Im trying to figure out how to get my navigation bar setup as most of the UI is coming together. I have setup my index.js and also a Route.js and then linked them with my different components like so:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import { Auth0Provider } from "./react-auth0-spa.js";
import { useAuth0 } from "./react-auth0-spa";
import Routes from "./Routes"
import config from "./utils/auth_config.json";
import { BrowserRouter } from "react-router-dom";
// A function that routes the user to the right place
// after login
const onRedirectCallback = appState => {
history.push(
appState && appState.targetUrl
? appState.targetUrl
: window.location.pathname
);
};
ReactDOM.render(
<Auth0Provider
domain={config.domain}
client_id={config.clientId}
redirect_uri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
<BrowserRouter>
<Routes />
</BrowserRouter>
</Auth0Provider>,
document.getElementById("root")
);
Routes.js
import React, { Component } from "react";
import { Router, Route, Switch, BrowserRouter } from "react-router-dom";
import {Link } from "react-router-dom";
import Profile from "./components/user/Profile";
import PrivateRoute from "./components/user/PrivateRoute";
import history from "./utils/history.js";
import HomePage from "./modules/HomePage.js";
import ProductPage from "./modules/ProductPage";
class Routes extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>
)
}
}
export default Routes;
but when i reload my site it just continues to say localhost:8080/ProductPage like its suppose to be the default, then when i manually enter localhost:8080/ and click on a button after linking it with
<Link to="ProductPage">
it will show on the tab localhost:8080/ProductPage but wont actually redirect me to the other component, i am just wondering what i am doing wrong?
Issue
You have your "home" route listed first in the Switch.
Switch
Renders the first child <Route> or <Redirect> that matches the location.
"/" is less specific and matches basically all routes, so even though the URL is "/ProductPage", "/" still matches it and HomePage is rendered.
Solution
Either move it after the other more specific routes or use the exact prop on it.
<Router history={history}>
<Switch>
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
<Route path="/" component={HomePage} />
</Switch>
</Router>
or
<Router history={history}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>

Categories