I'm learning React Router at the moment and would like to know if it's possible to import react component and routing though the API. I want to import the component each page.
I have this code:
import React, { lazy, useEffect, useState, Suspense} from 'react';
import shortid from 'shortid';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useHistory,
useLocation,
useParams
} from "react-router-dom";
It is component import function.
const importView = subreddit =>
lazy(() =>
import(`.${subreddit}`).catch(() => import(`./Component/ComponentNotFound/ComponentNotFound`))
);
const searchSubreddit = async query =>
fetch('api/header.json').then(_ => _.json());
export default function App({ subredditsToShow }) {
const [views, setViews] = useState([]);
const extractDataFromSearchResult = response =>
response.data.children.map(({ data }) => data);
useEffect(() => {
async function loadViews() {
const subredditsToShow = await searchSubreddit('react hooks').then(
extractDataFromSearchResult
);
const componentPromises = subredditsToShow.map(async data => {
const View = await importView(data.subreddit);
return <View key={shortid.generate()} {...data} />;
});
Promise.all(componentPromises).then(setViews);
}
loadViews();
}, [subredditsToShow]);
const Loading = () => {
return (
<>
<div style={{ height: "100vh", display: "flex", justifyContent: "center", alignItems: "center", margin: "0 auto" }} >
<img style={{ maxHeight: "600px", maxWidth: "800px" }} src="assets/icon/Loader.gif" />
</div>
</>
);
}
return (
<Router>
<Route exact path="/" subredditsToShow={views}>
<Route exact path="/about" subredditsToShow={views}>
</Route>
</Router>
);
}
What i am using it is good way or not? Please give your good feedback