Ariakit
/

Dialog with React Router

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

Post
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("/")}>

Stay tuned

Join 1,000+ subscribers and receive monthly tips & updates on new Ariakit content.

No spam. Unsubscribe anytime. Read latest issue