I am using the same component for three different routes:
<Router>
<Home path="/" />
<Home path="/home" />
</Router>
Is there anyway to combine it, to be like:
<Router>
<Home path=["/home", "/"] />
</Router>
For Reach Router: (https://reach.tech/router/example/)
With the exact sample shown, the only way I can see how to do this(on a single line) is with a wildcard.
To find a way to reproduce this without side effects, we would need to see the entire nav menu.
<Router>
<Home path="/*" />
<Chicken path="chicken">
</Router>
...
const Home = props => {
let urlPath = props["*"]
// URL: "/home"
// urlPath === "home"
// URL/: "/"
// urlPath ===""
}
You could continue with other paths below Home and the router would allow them to process.
Check out the the example using a wildcard and reach router on codesandbox, I wrote!
Note: This is a catch-all, but without parsing a parameter is the only single line solution I saw.
Some DrawBacks include Home rendering instead of '404', etc.
//This could be resolved with an if statement in your render
//It will not produce the intended URL either for /home, and I have not looked into that since it is not part of the question.. but if it matched props[*] I'm sure you could redirect or something.
You can read more about the Route Component for Reach Router.
https://reach.tech/router/api/RouteComponent
I wasn't happy with the wildcard solution from the documentation and #cullen-bond because I had to map many other paths and came up with this solution:
<Router>
{["/home", "/", "/other", "/a-lot-more"].map(page => <Home path={page} />)}
</Router>
Example: https://codesandbox.io/s/reach-router-starter-v1-forked-6f44c?file=/src/index.js
Depending on the situation you're dealing with, <Redirect /> could also make the work.
<Router>
<Redirect from="/" path="/home" noThrow />
<Home path="/home" />
</Router>
You can use a single component for mutiple paths, by using a array of routes.
code example :
import sampleComponent from './sampleComponent'; // single component for mutiple routes
<Router>
<Switch>
{["/pathname_1", "/pathname_2", "/pathname_3", "/pathname_4", "/pathname_5", "/pathname_6"].map(pathname => (<Route exact path={pathname} component={sampleComponent} />) )}
<Switch>
<Router>
Related
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
//App.js File
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
// import ReactDOM from "react-dom";
const App = () => {
return (
<Router >
<Routes>
<Route path="/" component={ Home }></Route>
</Routes>
</Router>
)
}
export default App;
**My any react router related code not working i don't know why it happend when i start insert some route in program so it show this error **
In V6, you can't use the component prop anymore. It was replaced in favor of element:
<Route path="/" element={<Home />}></Route>
More info in the migration doc.
I had the same problem. Replace component with element and it worked.
Replace this:
<Route path="/" component={HomePage} exact />
with this:
<Route path="/" element={<HomePage/>} exact />
I had the same error however my fix was slightly different
I had spelled element wrong.
<Route exact path='/MyGames' elemtent={<MyGames/>}/>
and this was the error it gave me in the browser console
Matched leaf route at location "/MyGames" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Very simple:
use element instead of component
wrap the your component like this: {<Home/>} instead of {Home}
<Route path="/" component={ <Home/> } />
in version 6:
component replaced with element and needs to close "</Route>"
<Route exact path="/" element={<AddTutorial />}></Route>
https://reactrouter.com/docs/en/v6/getting-started/overview
This is a common problem if you are using react-router-dom V6
To solve this it's simple
In your code
Replace component with element
Replace {home} with {}
This becomes...
<Route path="/" element={}>
This will definitely solve the problem.
If you're using react-router-dom 6 or above, you may have a routes array that includes parent and child routes. You may then try to open a route such as
/portal
and get this error because that component corresponds to a child route
/:customerid/portal
but you haven't read your routes (and their child routes) closely enough to see that.
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
//App.js File
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
// import ReactDOM from "react-dom";
const App = () => {
return (
<Router >
<Routes>
<Route path="/" component={ Home }></Route>
</Routes>
</Router>
)
}
export default App;
**My any react router related code not working i don't know why it happend when i start insert some route in program so it show this error **
In V6, you can't use the component prop anymore. It was replaced in favor of element:
<Route path="/" element={<Home />}></Route>
More info in the migration doc.
I had the same problem. Replace component with element and it worked.
Replace this:
<Route path="/" component={HomePage} exact />
with this:
<Route path="/" element={<HomePage/>} exact />
I had the same error however my fix was slightly different
I had spelled element wrong.
<Route exact path='/MyGames' elemtent={<MyGames/>}/>
and this was the error it gave me in the browser console
Matched leaf route at location "/MyGames" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Very simple:
use element instead of component
wrap the your component like this: {<Home/>} instead of {Home}
<Route path="/" component={ <Home/> } />
in version 6:
component replaced with element and needs to close "</Route>"
<Route exact path="/" element={<AddTutorial />}></Route>
https://reactrouter.com/docs/en/v6/getting-started/overview
This is a common problem if you are using react-router-dom V6
To solve this it's simple
In your code
Replace component with element
Replace {home} with {}
This becomes...
<Route path="/" element={}>
This will definitely solve the problem.
If you're using react-router-dom 6 or above, you may have a routes array that includes parent and child routes. You may then try to open a route such as
/portal
and get this error because that component corresponds to a child route
/:customerid/portal
but you haven't read your routes (and their child routes) closely enough to see that.
I'm trying to use REGEXP to help render a 404 page in a react app using the path. I cannot figure it out.
This is the REGEXP I want; I want to match IF:
The entire path is !== '/' && does not contain the word 'article'.
EDIT: Including code for clarification:
<Switch location={location} key={location.pathname}>
<Route path={["/commentisfree/article/:id", "/commentisfree"]}>
<Opinion />
</Route>
<Route path={["/sport/article/:id", "/sport"]}>
<Sport />
</Route>
<Route path={["/culture/article/:id", "/culture"]}>
<Culture />
</Route>
<Route path={["/lifestyle/article/:id", "/lifestyle"]}>
<Lifestyle />
</Route>
<Route path={["/signup", "/login"]}>
<Account />
</Route>
<Route path={["search/:search", "/search"]}>
<Search />
</Route>
<Route path={/REGEXP[if path !== "/" && path does NOT include the word "article"]/} component={ErrorDefault} />
<Route path={["/article/:id", "/"]}>
<Home />
</Route>
</Switch>
At the bottom you'll see I've had to put the 404 component just above my index route because the 404 is never hit if I use a catch all route, it simply navigates to the index route but maintains the incorrect URL.
For example, entering http://localhost:3000/mistake takes me to the index route. I don't want this as I rely on the urls to render modular components and it doesn't work if the path is incorrect.
So i need to force any non declared paths to a 404 page where i can display a message and a link back to the home page.
Are you using React router?
If so, you could use a catch-all route at the end of the route list, which will render a 404 page, like here: https://reactrouter.com/web/example/no-match
Edited: added link to React router documentation
The following function uses Regular Expression
const checkRegex = (urlString) => {
return (
new RegExp("/").test(urlString) && new RegExp("article").test(urlString)
);
};
You can also use the includes function for this
const checkRegex = (urlString) => {
return (
urlString.includes('article') && urlString.includes('/')
);
};
I'm learning React making a small single page app. Just added react-router-dom today and building it out to do routes and private routes. All is well except for one thing: When the user enters a malformed url in the browser bar, the user should be rerouted to the index (WORKS!), but the browser url bar is not updated on this redirect. Oddly enough, when I hit a private route while not authorized, the redirect DOES update the url bar. What am I missing?
router.js:
const PrivateRoute = ({auth: authenticated, component: Component, ...rest}) => (
<Route {...rest} render={(props) => (
authenticated === true
? <Component {...props} />
: <Redirect to='/login/'/>
)}/>
);
export default function Router() {
const auth = useSelector(isAuthenticated);
return (
<Switch>
<PrivateRoute auth={"auth"} path={"/dashboard/"} component={DashboardContainer}/>
<Route path={"/about/"} component={AboutContainer}/>
<Route path={"/login/"} component={LoginContainer}/>
<Route path={"/terms/"} component={TermsContainer}/>
<Route path={"/"} component={IndexContainer}/>
<Redirect push to={"/"}/>
</Switch>
);
}
I believe your issue is a result of not specifying that the paths should be exact matches, therefore any route will match with your route that is specified as:
<Route path={"/"} component={IndexContainer}/>
Try adding the exact prop to all of your routes (except for your redirect), and you should properly get redirected to the home page with the correct URL.
More details on the exact prop here: React : difference between <Route exact path="/" /> and <Route path="/" />
I used same component for different routes. When route changes, I want the component to be rendered.
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/hotels" component={HotelsPage} />
<Route path="/apartments" component={HotelsPage} />
</Switch>
When I change the route path from /hotels to /apartments, the component HotelsPage doesn't refresh.
What is the cool approach for this?
One of the ways you can get this sorted is by passing the props explicitly like :
<Route path="/hotels" component={props => <HotelsPage {...props} />} />
Firstly you can aggregate the Route into one like
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>
and secondly, your HotelsPage component is rendered both on /hotels, /apartments, it is similar case like path params, whereby the component doesn't mount again on path change, but updates thereby calling componentWillReceiveProps lifecycle function,
What you can do is implement componentWillReceiveProps like
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
console.log("here");
//take action here
}
}
DEMO
I guess just passing useLocation().pathname will resolve issue
useEffect(
() => {
// Your logics
});
}, [useLocation().pathname])