Dialog with React Router
Using React Router to create a modal Dialog that's controlled by the browser history.
import * as Ariakit from "@ariakit/react";
import {
Link,
MemoryRouter,
Outlet,
Route,
Routes,
useNavigate,
} from "react-router-dom";
import "./style.css";
function Tweet() {
const navigate = useNavigate();
const dialog = Ariakit.useDialogStore({
open: true,
setOpen(open) {
if (!open) {
navigate("/");
}
},
});
return (
<Ariakit.Dialog
store={dialog}
backdrop={<div className="backdrop" />}
className="dialog"
>
<Ariakit.DialogDismiss
as={Link}
to="/"
className="button secondary dismiss"
/>
<Ariakit.DialogHeading hidden>Tweet</Ariakit.DialogHeading>
<form className="form" onSubmit={dialog.hide}>
<label>
<Ariakit.VisuallyHidden>Tweet text</Ariakit.VisuallyHidden>
<Ariakit.Focusable
as="textarea"
className="input"
placeholder="What's happening?"
autoFocus
rows={5}
/>
</label>
<Ariakit.Button type="submit" className="button">
Tweet
</Ariakit.Button>
</form>
</Ariakit.Dialog>
);
}
function Home() {
return (
<>
<Link to="/tweet" className="button">
Tweet
</Link>
<Outlet />
</>
);
}
export default function Example() {
return (
// We're using MemoryRouter for demonstration purposes. But you can use
// BrowserRouter, HashRouter, etc. depending on your needs.
<MemoryRouter>
<Routes>
<Route path="/" element={<Home />}>
<Route path="/tweet" element={<Tweet />} />
</Route>
</Routes>
</MemoryRouter>
);
}
Controlling the Dialog state
To control the open state, you can pass the open
and setOpen
props to useDialogStore
. These props allow you to synchronize the dialog state with other state sources, such as the browser history.
In this example, since the dialog is only rendered when the route matches, we can pass open: true
to the store so that the dialog is always open. Then, we can use setOpen
to navigate back when the dialog is closed:
const navigate = useNavigate();
const dialog = Ariakit.useDialogStore({
open: true,
setOpen(open) {
if (!open) {
navigate("/");
}
},
});
You can learn more about controlled state on the Component stores guide.