-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added docs on how to created nested routes with a slot (#214)
- Loading branch information
1 parent
25266bf
commit 2e3973f
Showing
2 changed files
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# How to Create Nested Routes Using Slot in React Resource Router | ||
|
||
The React Resource Router library generally encourages you to keep your routing flat. However, there may be situations where you need nested components associated with different URLs. To accomplish this, you can create a Slot component. | ||
|
||
Here's how to do it: | ||
|
||
## Slot Component | ||
|
||
```js | ||
import { useRouter, Redirect } from 'react-resource-router'; | ||
|
||
// Define a object of URLs to Components. | ||
// Make sure the keys in this object match the URLs you intend to handle. | ||
const slots = { | ||
'url-one': ComponentOne, | ||
'url-two': ComponentTwo, | ||
}; | ||
|
||
const Slot = () => { | ||
const [{ route }] = useRouter(); | ||
const name = route.name; | ||
|
||
// If the specified slot doesn't exist, redirect to a 404 page | ||
if (!slots?.[name]) { | ||
return <Redirect to="/404" />; | ||
} | ||
|
||
// Dynamically load and render the component based on the current route name | ||
const DynamicComponent = slots[name]; | ||
return <DynamicComponent />; | ||
}; | ||
|
||
``` | ||
## Add Slot Component to Parent | ||
```js | ||
const Page = () => { | ||
return ( | ||
<div> | ||
<Slot> | ||
</div> | ||
) | ||
} | ||
``` |