'how to display html file when clicks on list of links in react?
I am trying to create a blog website as a learning practice curve. I am giving a local file path name of each html file in the list. I use the map to create a list of links. When I click on created list of links, those links are broken and redirect to home page. How to fix this part of issue?
Here is the Blog.js
const BlogPath = ["./blog/blog1.js", "./blog/blog1.js", "./blog/blog1.js","./blog/blog1.js"];
BlogPath.map((Path, index) =>
<div key={index}>
<Link to={/Path}>{Path}</Link>
</div>
)
Here is the App.js
function App() {
return (
<HashRouter >
<ScrollToTop />
<div className="App">
<Navigation/>
<Routes>
<Route exact path="/" element={ <Home /> }/>
<Route exact path="/blogList" element={<Blog />}/>
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>
</HashRouter>
);
}
I imported home and blog pages in App.js
import Home from './Home.js';
import About from './Blog.js';
Here is the Navigation.js
<>
<Navbar collapseOnSelect sticky='top' expand='sm' variant='dark' className='background color '>
<Container >
<Navbar.Toggle aria-controls='responsive-navbar-nav' />
<Navbar.Collapse className='mobile-nav' id='responsive-navbar-nav'>
<Nav className='me-auto'>
<Nav.Link as={NavLink} to="/" >Home</Nav.Link>
</Nav>
<Nav>
<Nav.Link as={NavLink} to="/blogList" >Blog</Nav.Link>
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</>
Here is the sample: link bold
Solution 1:[1]
Update the BlogList component to render more reader/user-friendly paths.
function BlogList() {
const BlogPath = ["blog1", "blog2", "blog1", "blog2", "blog3-4-5"];
return (
<>
{BlogPath.map((path, index) => (
<div key={index}>
<Link to={path}>{path}</Link>
</div>
))}
</>
);
}
This builds relative paths, i.e. "/blogList/blog1"
Add a route to the App to match and render this path:
function App() {
return (
<HashRouter>
<div className="App background">
<Navigation />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/blogList" element={<Bloglist />} />
<Route path="/blogList/:blog" element={<Blog />} /> // <--
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>
</HashRouter>
);
}
Create a Blog component to read the blog route path param so it can dynamically/lazily load the matching blog file:
const Blog = () => {
const { blog } = useParams();
const [BlogItem, setBlogItem] = React.useState();
React.useEffect(() => {
const BlogItem = React.lazy(() => import(`./blog/${blog}.js`));
setBlogItem(BlogItem);
}, [blog]);
return (
<>
<h1>Blog</h1>
{BlogItem && <BlogItem />}
</>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
