https://github.com/ihoverlord/react-router-sample
Sample React project to define routes with JSON config and redirecting users on 404
https://github.com/ihoverlord/react-router-sample
react react-router react-router-dom reactjs
Last synced: 12 months ago
JSON representation
Sample React project to define routes with JSON config and redirecting users on 404
- Host: GitHub
- URL: https://github.com/ihoverlord/react-router-sample
- Owner: ihoverlord
- Created: 2021-10-26T19:23:23.000Z (over 4 years ago)
- Default Branch: main
- Last Pushed: 2022-04-24T04:07:05.000Z (about 4 years ago)
- Last Synced: 2025-02-23T23:28:20.489Z (over 1 year ago)
- Topics: react, react-router, react-router-dom, reactjs
- Language: JavaScript
- Homepage:
- Size: 213 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
### React Routing sample
Sample project to test defining routes with JSON and handle redirecting on 404
1. Define routes in a JSON
```
const routes = {
'/default': {
component: Home
},
'/dashboard': {
component: Dashboard
},
'/profile': {
component: Profile
}
}
```
2. Create a function to define routes dynamically
```
const DefineRoutes = ({ routes }) => {
const paths = Object.keys(routes)
let location = useLocation();
// console.log({ location, has: routes[location.pathname] })
if (!routes.hasOwnProperty(location.pathname)) return
if (paths && paths.length > 0) {
return (
<>
{paths.map(path => )}
>
)
}
}
```
This function handles 404 and redirects the user to `/`
3. Define router and import the routes
```
```