Injecting routes programmatically into a JSX router switch statement - javascript

I've been trying to inject some JSX routes into a router switch statement without success.
Basically I'm trying to be able to reuse the method commonRoutes for different scenarios so I do not have to repeat myself...
However when I inject the routes as illustrated the routing does not behave as expected and multiple routes will trigger at the same time instead of conditionally...
hopefully the code illustrates clearly what I'm trying to do:
First try:
class App extends Component {
commonRoutes() {
return (
<Switch>
<Route path="/route1" component={Component1} />,
<Route path="/route2" component={Component2} />,
<Route path="/route3" component={Component3} />,
</Switch>
);
}
app() {
return (
<React.Fragment>
<Header />
<div className="app-content">
<Switch>
<Redirect exact from="/" to="/folder" />,
{this.commonRoutes()},
<Route path="*" component={NotFound} />
</Switch>
</div>
<Footer />
</React.Fragment>
);
}
render() {
let content = '';
if (this.props.component === ComponentList.COMPONENT_APP) {
return this.appFrame(this.app());
}
if(this.props.component === ComponentList.COMPONENT_FOLDER) {
return this.appFrame(this.folder());
}
if (this.props.component === ComponentList.COMPONENT_EVENT) {
return this.appFrame(this.event());
}
return content;
}
appFrame(content) {
return (
<React.Fragment>
<CssBaseline/>
<NotSupported support={[{ name: 'ie', minSupport: 11 }]}/>
<Favicon url={`${AppConfig.CONTEXT}favicon.ico`}/>
<MuiThemeProvider theme={theme}>
{content}
</MuiThemeProvider>
</React.Fragment>
);
}
//... code
}
Second try:
class App extends Component {
commonRoutes() {
return [
<Route path="/route1" component={Component1} />,
<Route path="/route2" component={Component2} />,
<Route path="/route3" component={Component3} />
];
}
app() {
return (
<React.Fragment>
<Header />
<div className="app-content">
<Switch>
<Redirect exact from="/" to="/folder" />,
{this.commonRoutes()},
<Route path="*" component={NotFound} />
</Switch>
</div>
<Footer />
</React.Fragment>
);
}
}
Another way that comes to mind is using an object with keys to store the JSX routes and looping with map, but several attempts did not do the trick either.
I appreciate any help or direction.

First thing,
let content = ''
if (...) {
return this.appFrame(this.app());
}
...
return content
The preceding code works but not the way you expect. You're trying to return the content after the condition is matched. This just return the this.appFrame(...).
let content = ''
if (...) {
content = this.appFrame(this.app());
}
...
return content
Now, this works the way you're expecting. It assigns the value to the content and finally return the content.
Now, to your issue, you should be using exact props to return only the required component:
commonRoutes() {
return (
[
<Route exact path="/route1" component={Component1} />,
<Route exact path="/route2" component={Component2} />,
<Route exact path="/route3" component={Component3} />
]
);
}
Also, ensure to use unique key when you render array of elements. In your case, it is [<Route key={'unique-key'} />,...].
And also remove path from here:
<Route path="*" component={NotFound} />
{/* -----^^ not required react router 4 */}

Related

Matched leaf route at location "/" does not have an element. This means it will render an <Outlet /> with a null value, so resulting in an empty page

the return statement gives a warning and addTodo & todos dont load. Switch is not supported anymore so I've replaced it with Routes but don't know how handle that return part
Does anybody know how do I solve this issue?
return (
<>
<Router>
<Header title="To Do List" />
<Routes>
<Route exact path= "/" render={() => {
return (
<>
<AddTodo addTodo = {addTodo} />
<Todos todos = {todos} onDelete={onDelete} />
</>
)
}
}>
</Route>
<Route exact path = "/about" element = {<About/>} />
</Routes>
<Footer />
</Router>
</>
);
Click to view warnings screenshot

How to detect matched route from a component outside of the <Route/> component that was matched using react-router?

I've got the following structure in my React app, using react-router-dom.
<Router>
<Header/>
<Main>
<AllRoutes> // THIS HANDLES THE SWITCH WITH ALL THE ROUTES
<Switch>
<Route exact path={ROUTES.HOME} component={Home}/>
<Route exact path={ROUTES.ABOUT} component={About}/>
<Route exact path={ROUTES.PRIVACY} component={Privacy}/>
// ETC
</Switch>
</AllRoutes>
</Main>
<Footer/> // <==== FOOTER NEEDS TO KNOW WHICH ROUTE HAS BEEN MATCH
<Router>
QUESTION
Footer needs to know what <Route/> has been match. What is the best pattern to achieve that?
OPTION #1
I found the useRouteMatch hook over on react router docs:
This would kind of work, but I don't think it is good enough for my situation. Because a URL string can match a route and still don't be a valid route at the same time.
For example:
Route: /:language/privacy
Valid route: /en/privacy
Not valid route that would also match: /notALanguage/privacy
Once a route has match, I usually need to check if it is valid before rendering a component page or the 404 page.
Like:
<Route exact path={"/:language/privacy"} render={(routeProps) => {
const possibleLanguage = routeProps.match.params.language;
if (possibleLanguage in LANGUAGES) {
return(
<PrivacyPage lang={possibleLanguage}/>
);
}
else {
return(
<Page404/>
);
}
}}/>
OPTION #2
What I'm thinking about doing is:
App.js calls useLocation. So it always re-render when there is a route change.
I could add a detectRoute function in App.js to do all the route checking beforehand.
And my AllRoutes component wouldn't need a component. I would implement a native JS switch and render the corresponding route.
This way I know upfront which <Route/> is going to match and I can pass it on to <Footer/> or any component that lives outside of the matched <Route/>.
Something like this:
SandBox Link
export default function App() {
console.log("Rendering App...");
const location = useLocation();
// THIS WOULD BE THE detectRoute FUNCTION
// I COULD EVEN USE THE useRouteMatch HOOK IN HERE
const matchedRoute =
location.pathname === ROUTE1
? "ROUTE1"
: location.pathname === ROUTE2
? "ROUTE2"
: "404";
return (
<div>
<div className="App">
<Link to={ROUTE1}>Route 1</Link>
<Link to={ROUTE2}>Route 2</Link>
<Link to={"/whatever"}>Route 404</Link>
</div>
<div>
<AllRoutes matchedRoute={matchedRoute} />
</div>
</div>
);
}
function AllRoutes(props) {
switch (props.matchedRoute) {
case "ROUTE1":
return <Route exact path={ROUTE1} component={Page1} />;
case "ROUTE2":
return <Route exact path={ROUTE2} component={Page2} />;
default:
return <Route exact path={"*"} component={Page404} />;
}
}
It works. But I would like to know if there's a proper way of doing this, 'cause this seems a bit weird and there might be something out there that was specifically designed for this.
Generally you want to either:
Wrap the components together
Create another switch to route them (and pass match params)
I put together a somewhat comprehensive example of the options. Hope that helps!
import React from "react";
import "./styles.css";
import { Switch, Link, Route, BrowserRouter } from "react-router-dom";
const hoc = (Component, value) => () => (
<>
<main>
<Component />
</main>
<Footer value={value} />
</>
);
const Wrapper = ({ component: Component, value }) => (
<>
<main>
<Component />
</main>
<Footer value={value} />
</>
);
const WrapperRoute = ({ component, value, ...other }) => (
<Route
{...other}
render={props => <Wrapper component={component} value={value} {...props} />}
/>
);
const Footer = ({ value }) => <footer>Footer! {value}</footer>;
const Header = () => <header>Header!</header>;
const Another = () => <Link to="/onemore">One More!</Link>;
const Home = () => <Link to="/other">Other!</Link>;
const OneMore = () => <Link to="/">Home!</Link>;
const Other = () => <Link to="/another">Another!</Link>;
export default () => (
<BrowserRouter>
<Header />
<Switch>
{/* You could inline it! */}
<Route
path="/another"
render={() => (
<>
<main>
<Another />
</main>
<Footer value="" />
</>
)}
/>
{/* You could use a custom route component (that uses an HOC or a wrapper) */}
<WrapperRoute
component={OneMore}
path="/onemore"
value="I got one more!"
/>
{/* You could use a Higher-Order Component! */}
<Route path="/other" component={hoc(Other, "I got other!")} />
{/* You could use a wrapper component! */}
<Route
path="/"
render={() => <Wrapper component={Home} value="I got home!" />}
/>
</Switch>
{/* You could have another switch for your footer (inline or within the component) */}
<Switch>
<Route
path="/another"
render={() => <Footer value="Switch footer another!" />}
/>
<Route
path="/other"
render={() => <Footer value="Switch footer other!" />}
/>
<Route
path="/onemore"
render={() => <Footer value="Switch footer onemore!" />}
/>
<Route path="/" render={() => <Footer value="Switch footer home!" />} />
</Switch>
</BrowserRouter>
);
Note the WrapperRoute would allow you to do validation on your match params before passing them through. You could do a Redirect if needed.
What I've ended up doing:
Since I'm using Redux, I added a piece of global state to keep track of the matched route.
And I dispatch actions to update that state from the render prop from the <Route/>'s component.
<Switch>
<Route key={index} exact path={"/some-route"} render={(routeProps) => {
// HERE I DISPATCH AN ACTION TO CHANGE THE STATE FOR THE CURRENT ROUTE
dispatch({
type: UPDATE_CURRENT_ROUTE,
payload: { name: "SOME_ROUTE_NAME" }
});
return (
<PrivacyPage
{...routeProps}
/>
);
}}/>
</Switch>
And now I can do on Footer.js:
function Footer() {
const currentRoute = useSelector((state) => state.currentRoute);
// RENDER FOOTER ACCORDINGLY TO THE CURRENT ROUTE
}

React Router path var with other paths as well, React cant tell the difference

I am setting up react router for different link in my project but the problem is I need react router to tell the difference between a user username variable and other paths.
For example:
baseUrl/admin
baseUrl/daniel
React doesnt know the difference. I will have a list of usernames in a db and would return an error if the user doesnt exist then that means the page does not exist.
This is my code:
class App extends Component{
render(){
return (
<Router>
<Route exact path="/" render={props => (
<React.Fragment>
<h1>Hey</h1>
</React.Fragment>
)}
/>
<Route exact path="/admin" render={props => (
<React.Fragment>
<h1>admin</h1>
</React.Fragment>
)}
/>
<Route path="/:user" component={UserComponent}
/>
</Router>
);
}
}
You can use the match.url property to choose which component render, for example:
<Route path="/:user" render={props => {
if(props.match.url === '/admin') {
return (
<React.Fragment>
<h1>Hey</h1>
</React.Fragment>
)
} else return (<UserComponent {...props} />)
}} />

Adding Redirects programmatically to React Router

I'm trying to add a bunch of redirects given an array of old routes and new routes so I came out with this component:
const redirectUrls = [
{ oldUrl: '/robin', newUrl: '/users' },
{ oldUrl: '/batman', newUrl: '/courses' }
];
export default Redirects = () => (
redirectUrls.map((url, index) => <Route key={index} exact path={url.oldUrl} render={() => <Redirect to={url.newUrl} />} />)
);
Which works fine, but I wanted it to be simplier so I removed the Route and left only the redirect like this:
export default Redirects = () => (
redirectUrls.map((url, index) => <Redirect key={index} exact from={url.oldUrl} to={url.newUrl} />))
But it won't work, all the redirects take me to the last route, which in this case is /courses, and its weird because if I do this:
<Switch>
...
<Route path='/users' exact component={users} />
<Route path="/courses" exact component={CoursesList} />
<Redirect from='/robin' to='/users' />
<Redirect from='/batman' to='/courses' /> // having them like this works fine
</Switch>
So it makes no sense for them fail when I create them with a map and I haven't found anything that leads to the cause nor to a solution.
You need to wrap the exported redirects in a switch:
const Redirects = () => {
return (
<Switch>
{redirectUrls.map(url => (
<Redirect from={url.oldUrl} to={url.newUrl} />
))}
</Switch>
);
};
export default Redirects;
That's only if you actually need to make a component out of them. It's not totally clear what you need and are looking for since export default Redirects = () => is invalid syntax. If you just want to bundle them as some variable you can do:
export const Redirects = redirectUrls.map(url => <Redirect from={url.oldUrl} to {url.newUrl} />);
// App.js
<Switch>
<Route path='/users' exact component={users} />
<Route path="/courses" exact component={CoursesList} />
...
{Redirects}
</Switch>
Did you try this with exact props
<Switch>
...
<Route path='/users' exact component={users} />
<Route path="/courses" exact component={CoursesList} />
<Redirect exact from='/robin' to='/users' />
<Redirect exact from='/batman' to='/courses' /> // having them like this works fine
</Switch>
Reference https://github.com/ReactTraining/react-router/issues/4837

React Router path wrongly matches

I'm using React v4.2 for my app, and it seems not to be matching the correct path for the routes:
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route path="/login" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <LoginForm {...props}/>
}
}
} />
<EnsureLoggedInContainer>
<Route exact path="/group" render={(props) => {
debugger;
return <GroupList {...props}/>
}
}/>
<Route exact path="/group/new" render={(props) => {
debugger;
return <GroupList {...props} modal={rr}/>;
}
} />
</EnsureLoggedInContainer>
</Switch>
</div>
</BrowserRouter>
</Provider>
I have some links in the app, on which I click and I redirect the client to new URL:
_onSubmit(values) {
const { history } = this.props;
this.props.createGroup(values, ({status}) => history.push('/group'));
}
I inspect the values of props.history.location.pathname and props.match.path and they don't match. Why is this happening? Why is the correct route not matched?
Update 1
The code for EnsureLoggedInContainer:
class EnsureLoggedInContainer extends Component {
componentDidMount() {
if (!isAuthenticated()) {
dispatch(setRedirectUrl(currentURL))
this.props.history.replace("/login")
}
}
render() {
if (isAuthenticated()) {
return(
<div>
<AppNavBar />
<ComponentsNavBar />
{this.props.children}
</div>
);
} else {
return <noscript />;
}
}
}
export default EnsureLoggedInContainer;
Update 2
I changed the router configuration code to the following:
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route exact path="/login" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <LoginForm {...props}/>
}
}
} />
<Route exact path="/register" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <RegisterForm {...props}/>
}
}
} />
<EnsureLoggedInContainer>
<Route exact path="/group" component={GroupList} modal={newGroupModal}/>
<Route exact path="/group/new" component={GroupList}/>
<Route component={Home} />
</EnsureLoggedInContainer>
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
And changed the last line of EnsureLoggedInContainer to :
export default withRouter(EnsureLoggedInContainer);
But still, I get Home always being rendered, and random URLs being matched to unrelated routes (e.g. /group/new)
As per the documentation:
A match object contains information about how a matched
the URL. match objects contain the following properties:
params - (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
isExact - (boolean) true if the entire URL was matched (no trailing characters)
path - (string) The path pattern used to match. Useful for building nested <Route>s
url - (string) The matched portion of the URL. Useful for building nested <Link>s
while
Locations represent where the app is now, where you want it to go, or
even where it was.
so if you are on say /group/new, location.pathname will give you /group/new whereas match.path will give your the Route path defined for the component in which you log it if it is matched
I finally managed to resolve the issue by using the private route pattern.

Categories

Resources