Redirecting to default route - javascript

Is there a way to load a default component for any given route? Lets say for example the only specified route I have is:
<Route path="/car/about-you" component={car} />
However, a user decides to navigate to /car/about-the-car but this route doesn't exist in my app, is there a way to load the default component i.e. in this example the car component?

Yup, add a Route at the end of your Switch component that has path='*'

You can do it by Redirect Component:
import { Route, Redirect} from 'react-router-dom';
...
<Redirect to="/car/about-you" />
it must be added at the end of the Switch Component.

Related

react router 6.4.3 nested routes with two different routes pointing to one route/component

Greeting,
I am make a website to display different products.
Assume I have the following routes:
perfume/a-specific-perfume
base/a-specific-base
These routes both display a single page with a single product, which is nice, but what if I have many different type of product. This would lead me to have the following routes:
perfume/a-specific-perfume
base/a-specific-base
water/...
.../...
It leads to repetitive works for each type of product.
Is there a way to ignore the root route? I tried using a wild card, "*/a-specific-perfume" or "*/p/a-specific-perfume", and it did not work. Any suggestion?
In react-router-dom#6 the wildcard character "*" is only valid at the end of a path and only serves to indicate that a route component can render descendent routes. You can use route path params for dynamic path segments.
Examples:
<Route path="/:type/a-specific-perfume" element={....} />
<Route path="/:type/a-specific-base" element={....} />
<Route path="/foo/:type/a-specific-perfume" element={....} />
<Route path="/bar/:type/a-specific-base" element={....} />
In each component (the element prop) use the useParams hook to access the route param value.
"/perfume/a-specific-perfume"
"/base/a-specific-base"
"/water/..."
"/.../..."
import { useParams } from 'react-router-dom';
...
const { type } = useParams(); // "perfume"|"base"|"water"|"..."|etc...

Leading Hashtag In A React Router Path

I'm refactoring an API front-end from jQuery to React and in order to keep the site backward-compatible, I have to keep the current URL formatting to match: www.site.com/#parameter, which has a leading hashtag in the pathname. The problem comes when trying to route the pathname to match this format, React Router doesn't recognize the route or render the corresponding components. When trying to console.log the useParams object, it returns undefined.
TLDR; How can I access a URL parameter that starts with a ‘#’?
import {Switch, Route} from "react-router-dom"
import Home from "./Home"
function Routes() {
return (
<div>
<Switch>
<Route exact path={`/#:parameter`}><Home/></Route>
</Switch>
</div>
)
}
export default Routes;
Have your heard about HashRouter from React Router? It's main functionality is to replace BrowserRouter to handle legacy systems and the overall route looks like this:
www.your-great-website.com/#route-name
That might be what you're looking for or it will give you a starting point hopefully
Here's the official docs from the React Router team - HashRouter

React Router V6 - NotFound component not working with dynamic parameter/slug?

I have installed "react-router-dom": "^6.0.0-beta.0" and created some page routes. Facing problems where the Page404 / NotFound component is not working if a page doesn't exist. For some reason when I am using dynamic page/post slug the component NotFound will not work if there is no page/post with this ID.
Is there an option inside React Router which solves this issue?
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import AllPosts from "components/AllPosts";
import SinglePost from "components/SinglePost";
import NotFound from "components/Page404";
const App = () => (
<Router>
<Routes>
<Route element={<AllPosts />} path="/" exact />
<Route element={<SinglePost />} path="/:slug" />
<Route element={<NotFound />} path="*" />
</Routes>
</Router>
);
export default App;
The Routes and Route component can't possibly know ahead of time that some dynamic path, "/someUnsupportedIdValue" for example, isn't a valid path to be handled by SinglePost.
The options you have here are:
Conditionally render some alternative UI in SinglePost, something along the lines of "A page by this ID isn't found".
Check if a page with matching ID exists, conditionally render that page, or a redirect (Navigate component replaced Redirect in v6) to your more generic 404 page (actually, a redirect to any "throw away" path that isn't explicitly handled already will land you on your 404 page). Or you can imperatively redirect with a navigate(to, { replace: true }).
Try to remove exact because was removed from v6 and make sure Page404 is the correct component or create Notfound.jsx
Check if the post not exists then redirect to Notfound page.

What is the right way to elevate props in React?

I apologize if my phrasing is wrong in the title. I've recently gotten cookies going in my app. My Topnav component needs access to them, but I'm unsure how to get them there.
App.js -
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Landing from './pages/Landing.js';
import LoginPage from './pages/LoginPage.js';
import Topnav from './pages/components/global/Topnav.js';
import './Global.css';
const App = props => (
<div>
<Topnav />
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/login' component={LoginPage} />
</Switch>
</div>
);
export default App;
My login component grabs the cookie from express (fetch) and then does a <Redirect to='/' />
This loads up my Landing page, where I'm able to grab the cookie, but how do I get the cookie to the Topnav? I saw an answer to something like this on stack where it seems like App.js grabs the cookie and passes it as a props to the components, but I don't see how it could if it never refreshes. I've thought about forcing an entire window refresh (which does work for Topnav when I do a refresh manually), but I've also seen answers here that say don't do that.
Use Context
You need to use the new context hook from react.
Create a context
This is a context that you can access around your app.
const MyContext = React.createContext(defaultValue);
Make a provider
Wrap the provider around your main app
<MyContext.Provider value={/* some value */}>
Access the context at the point at which you get the cookies
Use this in both your login and top nav to use the value from the context
const value = useContext(MyContext);
There are multiple ways to approach this.
Probably a beginner friendly one.
When your login Component does the login successfully you need to signal to the App Component about it probably using a onLoginSuccessful which can then read the cookie and do a setState with it and use this component state value in the props to your Topnav and Landing Component

React-Router Redirect not working at all, using React-Redux-Electron

I am trying to conditionally redirect to other pages within a modal using from react-router.
I have implemented withRouter at the bottom of the relevant components as well as in the connect function. I am currently not using the Reducer because I have a switch in a root modal component which catches a type and then renders a component. Below is a snippet from the switch.
case type.componentName
return <Redirect to='/component' />
break;
However, the new component is still not rendering. It is as if Redirect is not being registered at all. My route is below.
<App>
<Switch>
<Route path="/" component={HomePage} />
<Route component={upperComponent}>
<Route path="/modal" component={rootComponent}>
<Route path="/component" component={component} />
</Route>
</Route>
</Switch>
</App>
I was originally rendering pages by modifying the state through a boolean and based upon it, a different component would be rendered. This worked just fine but I would rather have some history from using React-Router when I render new pages. Is there something fundamentally wrong about how I am trying to call Redirect or should I use an entirely different strategy all together?
The code below was requested in a comment. This is in my container component and I have one per component.
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import rootComponent from '../components/rooComponent';
import { withRouter } from 'react-router-dom';
import * as rootComponentlActions from '../actions/rootComponent';
function mapStateToProps(state) {
return {
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(rootComponentActions, dispatch);
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(rootComponent));
I have also tried adding export default withRouter(component); as well in my child component to the root as well as in the root to test it out based upon some examples that I have read in the past. As far as I can tell, it made not difference, good or bad.

Categories

Resources