Our new URL based modal system allows you to do two things:
- Open a modal using Inertia's
router
using query params using a given key. - Add prefixed "state" parameters to the URL that clear when the modal is closed.
To open a modal when the registration
key is present in the URL, do the following:
<URLModal key="registration">
<p>Your content here.</p>
</URLModal>
To open them modal, use either Inertia's router
to set the query parameter, or use the handy openModal
function:
// Use `router` directly
router.reload({data: {registration: 214151232132}});
// Import and use the helper function
import {openModal} from '@/Shared/Modal.js'
openModal('registration', 214151232132);
You can also send someone directly to a modal by using a redirect()->route()
in Laravel:
return redirect()->route('my.router', ['registrations' => 214151232132]);
Note: i'm also hoping to add a redirect helper here, something like:
redirect()->route('my.route')->withModal('registrations', 214151232132);
When the modal opens, it fires an event, and you can listen for it with the visible
event:
<URLModal key="registration" on:visible={() => {
loadData();
}>
<p>Your content here.</p>
</URLModal>
You can use modal state to keep data in the URL bar, this means that when sharing the URL of a modal, you can re-open that modal in the exact same state as it was when the other person was viewing it.
Modal state is stored in the URL with the prefix of the modal key
- so if the modal is shown when the registration
key is in the URL, then if you add a state variable called tab
to the state object, it will add registration--tab=<value>
to the URL.
Please note: State disappears from the URL when that modal is closed.
Note: State variables are stored in the URL with a prefix, but they are accessible through the non-prefixed value.
registration--tab=<value>
in the URL will be accessible throughmodalState.tab
.
You can access the modalState
variable by binding it to a local variable so you can pass it to your sub-component.
<script>
let registrationModalState;
</script>
<URLModal bind:modalState={registrationModalState}>
<MyComponent {...registrationModalState} />
</URLModal>
You can set state using the inertia router
:
<script>
const ChangeTab = () => {
router.reload({
data: {
...$page.props.query, // make sure to spread the current query values.
tab: 'transactions' // add the value you want in
}
});
};
</script>
<button class="btn" on:click={ChangeTab}>Switch Tab</button>
...or you can use the helper function:
<script>
import {setModalState} from '@/Shared/Modal.js';
const ChangeTab = () => {
setModalState('registration', 'tab', 'transactions')
};
</script>
<button class="btn" on:click={ChangeTab}>Switch Tab</button>