Ariakit
/

Dialog with React Router

Using React Router to create a modal Dialog that's controlled by the browser history.

Open preview in a new tab
Post
Edit withViteNext.js
import * as Ariakit from "@ariakit/react";
import {
Link,
MemoryRouter,
Outlet,
Route,
Routes,
useNavigate,
} from "react-router-dom";
import "./style.css";
function Post() {
const navigate = useNavigate();
const close = () => navigate("/");
return (
onClose={close}
backdrop={<div className="backdrop" />}
className="dialog"
>
className="button secondary dismiss"
render={<Link to="/" />}
/>
<form className="form" onSubmit={close}>
<label>
className="input"
render={<textarea placeholder="What's happening?" rows={5} />}
/>
</label>
<Ariakit.Button type="submit" className="button primary">
Post
</form>
);
}
function Home() {
return (
<>
<Link to="/post" className="button">
Post
</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="/post" element={<Post />} />
</Route>
</Routes>
</MemoryRouter>
);
}

Components

Controlling the Dialog state

To control the open state, you can pass the open and onClose props to the Dialog component. 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 Dialog so that the dialog is always open. Then, we can use onClose to navigate back when the dialog is closed:

const navigate = useNavigate();
<Dialog open onClose={() => navigate("/")}>

Follow updates

Join 1,000+ subscribers and receive monthly updates with the latest improvements on Examples.

Read latest issue

No Spam. Unsubscribe at any time.