I have a list of pageNames and a list of pageUrls. I would like to create a router that generates a react component for each page in the list and uses a navbar with router links. I think the problem lies in the forEach function but I am not sure.
Can anyone tell what I am doing wrong?
Although I didn't find it helpful, here is a similar question.
import React, { useState } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
function App() {
const routes = [
{
name: 'home',
path: '/'
},
{
name: 'blog',
path: '/blog'
}
]
// translate (map) your array of objects into jsx
const routeComponents = routes.map(({name, path}) => ((
<Route key={name} path={path}>
<h1>{name}</h1>
</Route>
)))
return (
<div className="App" >
<Router>
<Navbar routes = {routes} />
<Switch>
{routeComponents}
</Switch>
</Router>
</div>
);
}
export default App;
function Navbar(props){
const links = props.routes.map(({name, path}) => (
<Link key={name} to={path}>{name}</Link>
))
return(
<div style={{justifyContent: "space-around", margin:"auto", display:"flex",justifyContent:"space-around",backgroundColor:"red"}}>
{links}
</div>
)
}
The issue you likely are seeing is due to the way the Switch component works. It renders the first matching Route or Redirect component. This means that within the Switch component path order and specificity matters! The home path "/" matches any path, so will always be matched and rendered.
You can avoid this by reordering the routes from more specific to less specific, or since you allude to wanting the routes to be dynamically generated from user interaction and stored in a state, specify the exact prop for all routes so all matching occurs exactly and the order and specificity is negated.
function App() {
const routes = [
{
name: 'home',
path: '/',
},
{
name: 'blog',
path: '/blog',
},
];
const routeComponents = routes.map(({name, path}) => (
<Route key={name} exact path={path}> // <-- exact prop to exactly match paths
<h1>{name}</h1>
</Route>
));
return (
<div className="App" >
<Router>
<Navbar routes={routes} />
<Switch>
{routeComponents}
</Switch>
</Router>
</div>
);
}
You're correct. forEach is populating your routes variable, which is an array. What you want is to build some JSX. This is traditionally done via map. You also do not need the useState calls, and you'll want to combine your page names and urls into a single object for easier management.
Here's some pseudocode that will put you on the path...
const routes = [
{
name: 'hello',
path: '/'
},
{
name: 'there',
path: '/there'
}
]
// translate (map) your array of objects into jsx
const routeComponents = routes.map(({name, path}) => (
<Route key={name} path={path}/>
))
// routeComponents is JSX. You originally had an array of JSX
<Switch>
{routeComponents}
</Switch>
// Same thing for your links
const navbar = routes.map(({name, path}) => (
<Link key={name} to={path}>{name}</Link>
))
<div>
{navbar}
</div>
update
some tweaks in above example to clarify it.
Update #2
Here's full code (jammed into 1 file).
Updated to react router v6.
test it here
import "./styles.css";
import React, { useState } from "react";
import {
BrowserRouter as Router,
Routes,
Route,
Link,
Outlet
} from "react-router-dom";
function Navbar({ routes }) {
const links = routes.map(({ name, path }) => (
<Link key={name} to={path}>
{name}
</Link>
));
return (
<div
style={{
justifyContent: "space-around",
margin: "auto",
display: "flex",
justifyContent: "space-around",
backgroundColor: "red"
}}
>
{links}
</div>
);
}
export default function App() {
const routes = [
{
name: "home",
path: "/"
},
{
name: "blog",
path: "/blog"
},
{
name: "about",
path: "/about"
}
];
// translate (map) your array of objects into jsx
const routeComponents = routes.map(({ name, path }) => (
<Route key={name} path={path} element={<h1>{name}</h1>} />
));
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Router>
<Routes>{routeComponents}</Routes>
<Navbar routes={routes} />
</Router>
{Outlet}
</div>
);
}
Related
I am using React Router v6 to build nested routes. I am facing 2 issues:
If I click a link which has children, the url should automatically go to the child, but only the component is rendered. The URL still says "/*".
Inside my child, I have a link which should get me the entire path. For example, it should be '/routeC/subC3/newRoute'
Please help.
This is my code.
App.js
import "./styles.css";
import {
Navigate,
Route,
Routes,
useMatch,
useLocation,
BrowserRouter,
Link,
Outlet
} from "react-router-dom";
import ComponentC from "./ComponentC";
import { Fragment } from "react";
const ComponentA = () => <p>Component A</p>;
const ComponentB = () => <p>Component B</p>;
const ComponentC1 = () => <p>I am in Component C1</p>;
const ComponentC2 = () => <p>I am in Component C2</p>;
const SubComponentC3 = () => <p>SubComponent C3</p>;
export const ComponentC3 = () => {
const location = useLocation();
const match = useMatch(location.pathname);
return (
<>
<p>Component C3</p>
<Link to={`${match.path}/newRoute`}>Take me to a new route</Link>
<Routes>
<Route
exact
path={`${match.path}/newRoute`}
element={<SubComponentC3 />}
/>
</Routes>
</>
);
};
export const componentCChildren = [
{
label: "Component C - 1",
code: "subC1",
component: ComponentC1
},
{
label: "Component C - 2",
code: "subC2",
component: ComponentC2
},
{
label: "Component C - 3",
code: "subC3",
component: ComponentC3
}
];
export const routeValues = [
{
label: "Component A",
path: "/routeA",
component: ComponentA,
children: []
},
{
label: "Component B",
path: "/routeB",
component: ComponentB,
children: []
},
{
label: "Component C",
path: "/routeC/*",
component: ComponentC,
children: componentCChildren
}
];
export default function App() {
return (
<div className="App">
<BrowserRouter>
{routeValues.map((item) => (
<Link key={item.path} to={item.path} style={{ paddingRight: "10px" }}>
{item.label}
</Link>
))}
<Routes>
{routeValues.map((route) => {
if (route.children.length > 0) {
return (
<Route
key={route.path}
path={route.path}
element={<route.component />}
>
{route.children.map((r, i, arr) => (
<Fragment key={r.code}>
<Route
path={`${route.path}/${r.code}`}
element={<r.component />}
/>
<Route
path={route.path}
element={<Navigate to={`${route.path}/${arr[0].code}`} />}
/>
</Fragment>
))}
</Route>
);
}
return (
<Route
key={route.path}
path={route.path}
element={<route.component />}
/>
);
})}
<Route path="*" element={<Navigate to="routeA" />} />
</Routes>
<Outlet />
</BrowserRouter>
</div>
);
}
ComponentC.js
import { useState } from "react";
import Tab from "#mui/material/Tab";
import Box from "#mui/material/Box";
import TabContext from "#mui/lab/TabContext";
import TabList from "#mui/lab/TabList";
import TabPanel from "#mui/lab/TabPanel";
import { useNavigate, useMatch, useLocation } from "react-router-dom";
import { componentCChildren } from "./App";
export default function ComponentC(props) {
const navigate = useNavigate();
const location = useLocation();
const match = useMatch(location.pathname);
const [tabId, setTabId] = useState(componentCChildren[0].code);
const handleTabChange = (e, tabId) => {
console.log("tabId", tabId);
navigate(`${tabId}`);
setTabId(tabId);
};
return (
<>
<p>Component C</p>
<TabContext value={tabId}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<TabList onChange={handleTabChange} aria-label="lab API tabs example">
{componentCChildren.map((tab) => {
return <Tab key={tab.code} value={tab.code} label={tab.label} />;
})}
</TabList>
</Box>
{componentCChildren.map((tab) => {
return (
<TabPanel key={tab.code} value={tab.code}>
{<tab.component />}
</TabPanel>
);
})}
</TabContext>
</>
);
}
This is a link to my sandbox.
Here's a refactor that leaves most of your route definitions in tact. The changes are mostly in how, and where, the routes are rendered.
App.js
Remove the routeValues children and change the "/routeC/*" string literal to "/routeC" since it's used for both the route path and the link. Append the "*" wildcard character to the route's path when rendering.
ComponentC3 will use relative links and paths to get to ".../newRoute" where "..." is the currently matched route path.
export const ComponentC3 = () => {
return (
<>
<p>Component C3</p>
<Link to="newRoute">Take me to a new route</Link>
<Routes>
<Route path="newRoute" element={<SubComponentC3 />} />
</Routes>
</>
);
};
export const routeValues = [
{
label: "Component A",
path: "/routeA",
component: ComponentA,
},
{
label: "Component B",
path: "/routeB",
component: ComponentB,
},
{
label: "Component C",
path: "/routeC",
component: ComponentC,
}
];
export default function App() {
return (
<div className="App">
<BrowserRouter>
{routeValues.map((item) => (
<Link key={item.path} to={item.path} style={{ paddingRight: "10px" }}>
{item.label}
</Link>
))}
<Routes>
{routeValues.map((route) => (
<Route
key={route.path}
path={`${route.path}/*`} // <-- append wildcard '*' here
element={<route.component />}
/>
))}
<Route path="*" element={<Navigate to="routeA" />} />
</Routes>
</BrowserRouter>
</div>
);
}
ComponentC.js
Here is where you'll render the componentCChildren as descendent routes. Within a new Routes component map componentCChildren to Route components each rendering a TabPanel component. Append the "*" wildcard matcher to the route path again so further descendent routes can be matched. Use a useEffect hook to issue an imperative redirect from "/routeC" to the first tab at "/routeC/subC1".
export default function ComponentC(props) {
const navigate = useNavigate();
useEffect(() => {
if (componentCChildren?.[0]?.code) {
// redirect to first tab if it exists
navigate(componentCChildren[0].code, { replace: true });
}
// run only on component mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const [tabId, setTabId] = useState(componentCChildren[0].code);
const handleTabChange = (e, tabId) => {
console.log("tabId", tabId);
navigate(tabId, { replace: true }); // just redirect between tabs
setTabId(tabId);
};
return (
<>
<p>Component C</p>
<TabContext value={tabId}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<TabList onChange={handleTabChange} aria-label="lab API tabs example">
{componentCChildren.map((tab) => {
return <Tab key={tab.code} value={tab.code} label={tab.label} />;
})}
</TabList>
</Box>
<Routes>
{componentCChildren.map((tab) => {
const TabComponent = tab.component;
return (
<Route
key={tab.code}
path={`${tab.code}/*`} // <-- append wildcard '*' here
element={
<TabPanel value={tab.code}>
<TabComponent />
</TabPanel>
}
/>
);
})}
</Routes>
</TabContext>
</>
);
}
in ComponentC just you need to pass <Outlet />. i updated your working demo pls check here
Following up from my question React router v6 and relative links from page within route, I'm trying to refactor the routes in our app to be more nested.
Trouble is that it doesn't seem possible to render a Route element recursively from data, because react-router insists that Route is directly inside Route and not wrapped in another component, and I cannot see how to render recursively (to arbitrary depth) any other way.
Reproduction on codesandbox.
import React from "react";
import { BrowserRouter, Routes, Route} from "react-router-dom";
import "./styles.css";
function GenericPage() {
return <div className="page">Generic page</div>;
}
const nav = {
slug: "",
title: "Home",
children: [
{
slug: "foo",
title: "Foo"
},
{
slug: "bar",
title: "Bar"
}
]
};
const RecursiveRoute = ({ node }) => {
return (
<Route path={node.slug} element={<GenericPage />}>
{node.children?.map((child) => (
<RecursiveRoute node={child} />
))}
</Route>
);
};
export default function App() {
return (
<BrowserRouter>
<Routes>
<RecursiveRoute node={nav} />
</Routes>
</BrowserRouter>
);
}
Error from react-router:
[RecursiveRoute] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
Issue
As the error indicates, you can't render Route components directly, they must be rendered directly by a Routes component, or another Route component in the case of nested routes.
Solution
Refactor RecursiveRoute to render a Routes component with a route for the current node and then map the node's children to routes that render the RecursiveRoute as an element.
Example:
function GenericPage({ title }) {
return (
<div className="page">
{title} page
</div>
);
}
const RecursiveRoute = ({ node }) => (
<Routes>
<Route
path={`${node.slug}/*`}
element={<GenericPage title={node.title} />}
/>
{node.children?.map((child) => (
<Route
key={child.slug}
element={<RecursiveRoute key={child.slug} node={child} />}
/>
))}
</Routes>
);
Suggestion
I strongly suggest not trying to roll your own custom route configuration and renderer, use the useRoutes hook instead to do all the heavy lifting for you.
Example:
Refactor the navigation config:
const nav = [
{
path: "/",
element: <GenericPage title="Home" />,
children: [
{
path: "foo",
element: <GenericPage title="Foo" />
},
{
path: "bar",
element: <GenericPage title="Bar" />
}
]
}
];
Pass the config to the useRoutes hook and render the result:
const routes = useRoutes(nav);
...
return routes;
Demo
I had the same puzzle to solve. In general I solve it by passing a function in Routes component. Here is my solution with few code snippets.
// in Routes.ts
interface IRoutes {
path: string
component: JSX.Element
children?: IRoutes[]
}
const routes: IRoutes[] = [
{
path: 'warehouse'
component: <WarehousePage />
children: [
{
path: 'products'
component: <ProductsPage />
},
{
path: 'units'
component: <UnitsPage />
},
]
},
]
// in AppRouter.tsx
const renderRoutesRecursive = (routes: IRoutes[]) =>
routes.map((route, index) =>
route.children ? (
renderRoutesRecursive(route.children)
) : (
<Route
key={index}
path={route.path}
element={route.component}
/>
),
)
const renderRoutes = useMemo(() => renderRoutesRecursive(routes), [routes])
return (
<Routes>
<Route path='/' element={<Layout />}>
{renderRoutes}
</Route>
</Routes>
)
// in Layout.tsx
const Layout = () => {
return (
<>
<Header />
<Navigation />
<Main>
<Outlet />
</Main>
<Footer />
</>
)
}
I have a page which has three routes. The 3rd route has a tab component which handles 3 sub routes. I am able to navigate to Route 3, but unable to view the tabs and unable to render the content under each tab.
Please advice.
This is my code:
import "./styles.scss";
import React, { useState } from "react";
import { Redirect, Route, Switch } from "react-router";
import { BrowserRouter, Link } from "react-router-dom";
import { Tab, Tabs } from "#blueprintjs/core";
const ComponentC1 = () => <p>Component C1</p>;
const ComponentC2 = () => <p>Component C2</p>;
const ComponentC3 = () => <p>Component C3</p>;
const componentCRoutes = [
{
label: "Component C - 1",
code: "subC1",
component: ComponentC1
},
{
label: "Component C - 2",
code: "subC2",
component: ComponentC2
},
{
label: "Component C - 3",
code: "subC3",
component: ComponentC3
}
];
const ComponentA = () => <p>Component A</p>;
const ComponentB = () => <p>Component B</p>;
const ComponentC = (props) => {
const [tabId, setTabId] = useState(componentCRoutes[0].label);
const handleTabChange = (tabId) => setTabId(tabId);
return (
<>
<p>Component C</p>
<Tabs onChange={handleTabChange} selectedTabId={tabId}>
{componentCRoutes.map((tab) => {
return (
<Tab
key={tab.code}
id={tab.label}
title={
<Link to={`/${props.match.url}/${tab.code}`}>{tab.label}</Link>
}
/>
);
})}
</Tabs>
{(() => {
const { component, code } = componentCRoutes.find(
(item) => item.label === tabId
);
return (
<Route path={`${props.match.url}/${code}`} component={component} />
);
})()}
<Route exact path={props.match.url}>
<Redirect to={`${props.match.url}/${componentCRoutes[0].code}`} />
</Route>
</>
);
};
const routes = [
{ label: "Component A", path: "/routeA", component: ComponentA },
{ label: "Component B", path: "/routeB", component: ComponentB },
{ label: "Component C", path: "/routeC", component: ComponentC }
];
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<BrowserRouter>
{routes.map((item) => (
<Link key={item.path} to={item.path} style={{ paddingRight: "10px" }}>
{item.label}
</Link>
))}
<Switch>
{routes.map((route) => {
return (
<Route
key={route.path}
exact
path={route.path}
component={route.component}
/>
);
})}
<Route exact path="/">
<Redirect to="/routeA" />
</Route>
</Switch>
</BrowserRouter>
</div>
);
}
This is my codesandbox link
Please advice.
Issues:
Tabs in ComponentC are not working correctly as React-Router Link. It can be fixed using history.push in Tab's onChange handler.
You have not defined Routes in your nested component properly. You are using find to define the Route, that looks dirty. It can be fixed using a Switch and Route in nested component i.e. ComponentC
You used Route and Redirect to make default paths. That can be simplified as well.
You used props.match.url and props.match.path incorrectly. props.match.url (URL) should be used in Link or history.push and props.match.path (PATH) should be used in path of your nested Routes declarations.
Solution:
After fixing all the issues mentioned above, Here is the working code:
(Also, note that the Route that has nested routes should not be marked exact={true})
Main Routes:
const routes = [
{ exact: true, label: "Component A", path: "/routeA", component: ComponentA },
{ exact: true, label: "Component B", path: "/routeB", component: ComponentB }
{ exact: false, label: "Component C", path: "/routeC", component: ComponentC }
// ^ it is false because it has nested routes
];
// JSX
<BrowserRouter>
{routes.map((item) => (
<Link key={item.path} to={item.path}>
{item.label}
</Link>
))}
<Switch>
{routes.map((route) => {
return (
<Route
key={route.path}
exact={route.exact}
path={route.path}
component={route.component}
/>
);
})}
<Redirect exact from="/" to="/routeA" />
</Switch>
</BrowserRouter>
And Here is nested routes declarations inside ComponentC:
const routes = [
{
label: "Component C1",
code: "subC1",
component: ComponentC1
},
{
label: "Component C2",
code: "subC2",
component: ComponentC2
},
{
label: "Component C3",
code: "subC3",
component: ComponentC3
}
];
export default function ComponentC(props) {
const [tabId, setTabId] = useState(routes[0].code);
const handleTabChange = (tabId) => {
props.history.push(`${props.match.url}/${tabId}`);
setTabId(tabId);
};
return (
<>
<Tabs onChange={handleTabChange} selectedTabId={tabId}>
{routes.map((tab) => {
return <Tab key={tab.code} id={tab.code} title={tab.label} />;
})}
</Tabs>
<Switch>
{routes.map((route) => (
<Route
key={route.code}
exact
path={`${props.match.path}/${route.code}`}
component={route.component}
/>
))}
<Redirect
exact
from={props.match.url}
to={`${props.match.url}/${routes[0].code}`}
/>
</Switch>
</>
);
}
Here is full demo on Sandbox.
I am trying to build a simple router for my React application, which would consist of a few routes generated from an array of objects and a static 404 route. The requirement is that transitions between every route must be animated.
I am using react-router for the browser and react-transition-group.
I want to achieve something like this (stripped-down, incomplete pseudo-code):
const routes = [
{ path: "/", component: Home },
{ path: "/about", component: About },
{ path: "/contact", component: Contact }
];
const createRoute = (route) => {
return (
<CSSTransition className="page" timeout={300}>
<Route path={route.path} exact component={route.component} />
</CSSTransition>
);
}
<Router>
{routes.map(createRoute)}
<CSSTransition className="page" timeout={300}>
<Route component={PageNotFound} />
</CSSTransition>
</Router>
A full version of this code can be found on this Codesandbox:
https://codesandbox.io/s/react-router-switch-csstransition-catch-all-route-bug-forked-qzt9g
I need to use the <Switch> component to prevent the 404 route from showing in all the other routes of the application, but as soon as I add the <Switch>, the animations stop working.
In the example above, you will see that the animations don't work when used with <Switch>, despite following the guides from official docs of both react-router and react-transition-group.
However, they work perfectly without the use of the <Switch>, but then of course I end up with 404 route showing all the time.
Expected result:
animated transitions between all routes, those dynamically created as well as the static 404 page
Actual result:
no animations at all or animations with 404 route always showing
I have spent the entire day trying to find a solution to the problem that I encountered. Unfortunately I can't seem to find anything that would remotely help me fix the issue I'm facing, and I've searched on Google, Stack Overflow, Medium and finally I'm back here hoping someone can help me out please.
In order to have the animation working with the Switch component, you have to pass the right location with withRouter to the CSSTransition, coupled with TransitionGroup component.
I've modified you sandbox code with the following working solution:
import React from "react";
import ReactDOM from "react-dom";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import {
BrowserRouter as Router,
Route,
Switch,
Link,
withRouter
} from "react-router-dom";
import "./styles.css";
const rootElement = document.getElementById("root");
const components = {
Home: () => <div>Home page</div>,
About: () => <div>About the company</div>,
Contact: () => <div>Contact us</div>,
NotFound: () => <div>404</div>,
Menu: ({ links, setIsSwitch }) => (
<div className="menu">
{links.map(({ path, component }, key) => (
<Link key={key} to={path}>
{component}
</Link>
))}
<Link to="/404">404</Link>
</div>
)
};
const routes = [
{ path: "/", component: "Home" },
{ path: "/about", component: "About" },
{ path: "/contact", component: "Contact" }
];
const createRoutes = (routes) =>
routes.map(({ component, path }) => {
const Component = components[component];
const nodeRef = React.createRef();
return (
<Route key={path} path={path} exact>
{({ match }) => {
return (
<div ref={nodeRef} className="page">
<Component />
</div>
);
}}
</Route>
);
});
const AnimatedSwitch = withRouter(({ location }) => (
<TransitionGroup>
<CSSTransition
key={location.key}
timeout={500}
classNames="page"
unmountOnExit
>
<Switch location={location}>{createRoutes(routes)}</Switch>
</CSSTransition>
</TransitionGroup>
));
ReactDOM.render(
<React.StrictMode>
<Router>
<components.Menu links={routes} />
<AnimatedSwitch />
</Router>
</React.StrictMode>,
rootElement
);
This article explains in detail the reasoning behind it: https://latteandcode.medium.com/react-how-to-animate-transitions-between-react-router-routes-7f9cb7f5636a.
By the way withRouter is deprecated in react-router v6.
So you should implement that hook in your own.
import { useHistory } from 'react-router-dom';
export const withRouter = (Component) => {
const Wrapper = (props) => {
const history = useHistory();
return (
<Component
history={history}
{...props}
/>
);
};
return Wrapper;
};
See Deprecated issue discussion on GitHub: https://github.com/remix-run/react-router/issues/7156.
A quick fix is you can do following
<Switch>
<Route
path={"/:page(|about|contact)"}
render={() => createRoutes(routes)}
/>
<Route>
<div className="page">
<components.NotFound />
</div>
</Route>
</Switch>
Obviously not the most elegant nor scalable solution. But doable for a small react site.
Here's the forked codesandbox of working code.
https://codesandbox.io/s/react-router-switch-csstransition-catch-all-route-bug-forked-dhv39
EDIT: I was checking router.location.key first, but reaching through address bar was causing 404 page to render every page, so this is safer.
You can pass router as props to pages and conditionally render 404 page by checking router.location.pathname
export const routes = [
...all of your routes,
{
path: "*",
Component: NotFound,
},
]
{routes.map(({ path, pageTitle, Component }) => (
<Route key={path} exact path={path}>
{router => (
<CSSTransition
in={router.match !== null}
timeout={400}
classNames="page"
unmountOnExit
>
<div className="page">
<Component router={router} />
</div>
</CSSTransition>
)}
</Route>
))}
And in your 404 component, you need to check the path of the current route if it is available around all routes:
import { routes } from "../Routes";
const checkIfRouteIsValid = path => routes.findIndex(route => route.path === path);
export default function NotFound(props) {
const pathname = props.router.location.pathname;
const [show, setShow] = useState(false);
useEffect(() => {
setShow(checkIfRouteIsValid(pathname) === -1);
}, [pathname]);
return (
show && (
<div>Not found!</div>
)
);
}
Codesandbox
Hi, if I create an array of routes with React Router which has the HOC of <MainRoute /> which wraps the actual <Component /> with <Main/>, on every path change <Main/> is getting remounted and hence the useEffect hook is getting recalled.
Is there a way to only remount the <Component /> not <Main/> itself? Maybe some kind of memoization?
Mapping over routes is very convenient, however it seems to re-map everything on the location change which doesn't happen if I just hardcode every route like <MainRoute path=.. component=.. /> inside the <Switch />.
Help highly appreciated,
Cheers
import React from "react";
import { Route, Switch, BrowserRouter, Link } from "react-router-dom";
import styled from "styled-components";
const Layout = styled.div`
margin: auto;
width: 0;
`;
const Main = ({ children, ...props }) => {
React.useEffect(() => {
console.log("API REQUEST - Called every time");
}, []);
return <Layout>{React.cloneElement(children, props)}</Layout>;
};
const MainRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
return (
<Main path={rest.path}>
<Component {...props} />
</Main>
);
}}
/>
);
};
export default function App() {
return (
<BrowserRouter>
<Switch>
{routes.map(({ path, component }) => (
<MainRoute key={path} path={path} component={component} exact />
))}
</Switch>
</BrowserRouter>
);
}
const Home = () => (
<>
Home <Link to="/other">Other</Link>
</>
);
const Other = () => (
<>
Other <Link to="/">Home</Link>
</>
);
const routes = [
{ path: "/", component: Home },
{ path: "/other", component: Other }
];