How to do non-existent routes redirect to homepage in react router dom? - javascript

I would like all routes other than those registered below to direct me to the main page.
example:
testexample.com/contact
-> Returns me to the contact page
testexample.com/sdlskdsd
-> Route does not exist, return to main page
import {
BrowserRouter,
Routes,
Route
} from 'react-router-dom'
import Footerpage from './components/footerpage/Footerpage';
import Navegation from './components/navegation/Navegation';
import Homepage from './pages/Homepage';
import Contact from './pages/contact/Contact';
import Bookpage from './pages/bookpage/Bookpage';
import Success from './pages/contact/status/Success';
import Error from './pages/contact/status/Error';
function App() {
return (
<BrowserRouter>
<Navegation />
<Routes>
<Route path='/' exact element={<Homepage />} />
<Route path='/contact' exact element={<Contact />} />
<Route path='/contactsuccess' exact element={<Success />} />
<Route path='/contacterr' exact element={<Error />} />
<Route path='/bookpage' exact element={<Bookpage />} />
</Routes>
<Footerpage />
</BrowserRouter>
);
}
export default App;

Redirect unknown/unhandled routes to the "/" path with the Navigate component.
<Route path="*" element={<Navigate to="/" replace />} />
Also, in RRDv6 all routes are now always exactly matched, there is no longer any exact prop, so these should all be removed.
Full routes example:
import {
BrowserRouter,
Routes,
Route,
Navigate
} from 'react-router-dom';
...
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/contact' element={<Contact />} />
<Route path='/contactsuccess' element={<Success />} />
<Route path='/contacterr' element={<Error />} />
<Route path='/bookpage' element={<Bookpage />} />
<Route path="*" element={<Navigate to="/" replace />} /> // <-- redirect
</Routes>

Add a default route
import {
BrowserRouter,
Routes,
Route
} from 'react-router-dom'
import Footerpage from './components/footerpage/Footerpage';
import Navegation from './components/navegation/Navegation';
import Homepage from './pages/Homepage';
import Contact from './pages/contact/Contact';
import Bookpage from './pages/bookpage/Bookpage';
import Success from './pages/contact/status/Success';
import Error from './pages/contact/status/Error';
function App() {
return (
<BrowserRouter>
<Navegation />
<Routes>
<Route path='/' exact element={<Homepage />} />
<Route path='/contact' exact element={<Contact />} />
<Route path='/contactsuccess' exact element={<Success />} />
<Route path='/contacterr' exact element={<Error />} />
<Route path='/bookpage' exact element={<Bookpage />} />
<Route element={<Homepage />} />
</Routes>
<Footerpage />
</BrowserRouter>
);
}
export default App;

Another way of doing it
<Routes>
<Route path='/' exact element={<Homepage />} />
<Route path='/contact' exact element={<Contact />} />
<Route path='/contactsuccess' exact element={<Success />} />
<Route path='/contacterr' exact element={<Error />} />
<Route path='/bookpage' exact element={<Bookpage />} />
<Route path='/*' element={<Homepage />} />
</Routes>

Related

Nested Routing in react js. Make default component on user click

<BrowserRouter>
<Routes>
<Route path='/' element={<Home />} />
<Route path='users' element={<Users />} >
<Route path='user1' element={<User1 />} />
<Route path='user2' element={<User2 />} />
<Route path='user3' element={<User3 />} />
</Route>
</Routes>
</BrowserRouter>
____________________________________________
import React from 'react'
import { NavLink, Outlet } from 'react-router-dom'
function Users() {
return (
<div>
<NavLink to='user1'>User1</NavLink>
<NavLink to='user2'>User2</NavLink>
<NavLink to='user3'>User2</NavLink>
<Outlet/>
</div>
)
}
export default Users;
I am using react router dom#6. While hitting users url wanted to make user1 as a default component to show on screen along with users and it also redirects url to users/user1
You can use the <Navigate> element.
<Route path='users' element={<Users />} >
<Route path='' element={<Navigate to="users/user1" replace/>} />
<Route path='user1' element={<User1 />} />
<Route path='user2' element={<User2 />} />
<Route path='user3' element={<User3 />} />
</Route>

React Router Dom v6 HashRouter basename not working

i want to use that Hashrouter, but when i try, i got this error:
<Router basename="/admin"> is not able to match the URL "/" because it does not start with the basename, so the <Router> won't render anything.
i put "Homepage": "./admin" in packedjson
but when i use BrowserRouter, its render normaly, can anyone explain why, please?
The code i'm using to try to understand router v6:
import "./styles.css";
import {
BrowserRouter,
Routes,
Route,
Navigate,
Outlet,
Link,
HashRouter,
} from "react-router-dom";
const ProtectedRoutes = () => <Outlet />;
const Configuration = () => <h1>Configuration</h1>;
const SummaryPage = () => <h1>SummaryPage</h1>;
const Dashboard = () => <h1>Dashboard</h1>;
const Appointments = () => <h1>Appointments</h1>;
const NotFound = () => <h1>NotFound</h1>;
export default function App() {
return (
<HashRouter basename="/admin">
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Link to="/dashboard" className="link">
Home
</Link>
</div>
<Routes>
<Route path="/configuration/configure" element={<Configuration />} />
<Route path="/configuration" element={<SummaryPage />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/appointments" element={<Appointments />} />
<Route path="/" element={<Navigate replace to="/configuration" />} />
<Route path="*" element={<NotFound />} />
</Routes>
</HashRouter>
);
}
There mostly seems to be a misunderstanding with how the basename prop is applied in the router, specifically the HashRouter. With the HashRouter the basename prop is a value that is applied against the paths the app is handling, not against the domain path where the app is served/running.
Example:
<HashRouter basename="/admin">
<Link to="/dashboard" className="link"> // renders <a href="#/admin/dashboard">
Dashboard
</Link>
...
<Routes>
<Route path="/configuration">
<Route path="configure" element={<Configuration />} />
<Route index element={<SummaryPage />} />
</Route>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/appointments" element={<Appointments />} />
<Route path="/" element={<Navigate replace to="/configuration" />} />
<Route path="*" element={<NotFound />} />
</Routes>
</HashRouter>
In other words, the basename prop value is applied to the URL hash and not the URL path, i.e. it's applied to everything after the hash.
mysite.com/someSubdomain/#/admin /something / ... more nested paths
|--domain-|--subdomain--|#|--------------hash-----------------|
| | | |basename| app path | ... app subpaths
If you are wanting the "/admin" to show up prior to the hash, then this is part of where the entire app is deployed to and served up from. In this case the app needs to be deployed to mysite.com in a "/admin" subdirectory. You also won't need to specify the basename="/admin" if you don't want an additional "/admin" to show up in the app's routing.
mysite.com/admin/#/something
...
<HashRouter>
<Link to="/dashboard" className="link"> // renders <a href="#/dashboard">
Dashboard
</Link>
...
<Routes>
<Route path="/configuration">
<Route path="configure" element={<Configuration />} />
<Route index element={<SummaryPage />} />
</Route>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/appointments" element={<Appointments />} />
<Route path="/" element={<Navigate replace to="/configuration" />} />
<Route path="*" element={<NotFound />} />
</Routes>
</HashRouter>
update: Not a solution =[ basename not works in Routes, and hashrouter not working with basename
Some solution here:
https://github.com/remix-run/react-router/issues/7128#issuecomment-582591472
but i don't know if it's the best one.
// url where new router is created: https://my-site/who/users
const RootModule = () => {
return (
<main>
<BrowserRouter>
<Routes basename="who/users">
<nav>
<Link to="">Home</Link>
<Link to="who/users/about">About</Link>
<Link to="who/users/users">Users</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="who/users/about" element={<About />} />
<Route path="who/users/users" element={<Users />} />
</Routes>
</Routes>
</BrowserRouter>
</main>
);
};
and here working
SANDBOX

React Router with other components

I have one problem that I can not understand. I am totally a beginner in ReactJS so I hope you will help me. I made Navigation with React Router and it works, but when I start to render all other components in App.js nothings happened. When I am routing through the navigation bar it is rendering, but on scroll, nothing happened.
This is my App.js without rendering other components that work normally, but when I add something like , it is the same without scroll.
my code :
const App = () => {
return (
<div>
<Router>
<Topbar />
<About />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/service" component={Service} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
</div>
);
};
export default App;
You need to use a redirect
1/ import {Redirect} from 'react-router-dom';
2/ Change your Home route to <Route exact path="/home" component={Home} />
3/ Add the redirect (It must be the last route)
<Route exact path="/">
<Redirect to="/home" />
</Route>
Example :
import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from 'react-router-dom';
import Home from './Home';
import About from './About';
import Service from './Service';
import Portfolio from './Portfolio';
import Contact from './Contact';
const App = () => {
return (
<Router>
<Switch>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/service" component={Service} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/contact" component={Contact} />
{/* Redirect */}
<Route exact path="/">
<Redirect to="/home" />
</Route>
</Switch>
</Router>
);
};
export default App;
If you want to check a demo : Stackblitz

How to have react load Home page and then route to others

I have a basic portfolio app that has the following structure:
App.js
function App() {
return (
<BrowserRouter>
<LeftNav />
<RightNav />
<NavBar />
<Switch>
<Route component={Home} path='/' exact />
<Route component={About} path='/about' />
<Route component={Project} path='/projects' />
<Route component={Contact} path='/contact' />
</Switch>
</BrowserRouter>
)
}
When I click on the link to go the production site it only renders the LeftNav, RightNav, and Navbar. I have to click on the Home component to have the Home Screen load.
I then tried putting the Home component outside of to look like:
function App() {
return (
<BrowserRouter>
<LeftNav />
<RightNav />
<NavBar />
<Home />
<Switch>
<Route component={Home} path='/' exact />
<Route component={About} path='/about' />
<Route component={Project} path='/projects' />
<Route component={Contact} path='/contact' />
</Switch>
</BrowserRouter>
)
}
This is the action I want upon clicking on the link, however then my components don't load. How do I structure this so that the Home component loads up on the initial click and that I'm able to navigate to other pages?
Your first version is good, just add a redirect and change the home path
import React from 'react';
import {BrowserRouter, Switch, Route, Redirect} from 'react-router-dom'; // import Redirect
function App() {
return (
<BrowserRouter>
<LeftNav />
<RightNav />
<NavBar />
<Switch>
<Route component={Home} path='/home' exact /> // change the path
<Route component={About} path='/about' />
<Route component={Project} path='/projects' />
<Route component={Contact} path='/contact' />
<Route path="/" exact> // Add the redirect
<Redirect to="/home" />
</Route>
</Switch>
</BrowserRouter>
)
}
You will have to exchange your home path from being the default page:
<Route component={Home} path='/' exact />
to
<Route component={Home} path='/home' exact />
and then add a 'Redirect' to your App.js :
<Route path="/" exact>
<Redirect to="/home" />
</Route>

route redirects to nothing react-router 4 [duplicate]

This question already has answers here:
Route is not matched
(3 answers)
Closed 5 years ago.
I'm not sure why everything is redirecting to a blank page:
I'm using:
"react-router": "^4.2.0",
"react-router-dom": "^4.1.1",
App.js
import { BrowserRouter, Route, Switch } from 'react-router-dom';
class Container extends Component{
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default class App extends Component {
render() {
return (
<BrowserRouter onUpdate={onUpdate}>
<Switch>
<Route component={HomePageContainer} exact path="/" />
<Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
<Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
<Route component={Container} path="/" />
<Route component={NotFound} path="*" />
</Switch>
</BrowserRouter>
);
}
}
Homepage route to '/' is working fine.
What's not working are all the other routes.
For example when a user clicks a hyperlink that redirects to these routes or other routes other than the default route, I'm getting a blank page:
<Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
<Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
Here is how my routes were working when I was using react-router v3:
<Router history={browserHistory} onUpdate={onUpdate}>
<Route path="/">
<IndexRoute component={HomePageContainer} />
<Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
<Route component={About} name="about" path="about" />
<Route component={JobList} name="jobs" path="jobs" />
</Route>
<Route component={Container} path="/" />
<Route component={NotFound} path="*" />
</Router>
Note that I also added the new route for companydetail just recently.
All your paths needs to be with respect to to base path i.e. /
Change your router config to
<Switch>
<Route component={HomePageContainer} exact path="/" />
<Route component={CompanyDetailContainer} name="companydetail" path="/interviews/companies/:companyId/details" />
<Route component={InterviewContainer} name="interview" path="/interviews/companies/:companyId" />
<Route component={Container} path="/" />
<Route component={NotFound} path="*" />
</Switch>
Try wrapping your router in an anonymous function.
const App = () => (
<BrowserRouter onUpdate={onUpdate}>
<Switch>
<Route component={HomePageContainer} exact path="/" />
<Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
<Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
<Route component={Container} path="/" />
<Route component={NotFound} path="*" />
</Switch>
</BrowserRouter>
)

Categories

Resources