Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind react route to a shown dialog?

React Router has a good tutorial on Nested Routes.

And it's pretty easy to create and understand.

However, I want to bind a route to a dialog.

Basically I have a list of customers at /customers and I have a New button on it. When it's clicked a form is shown inside a dialog. I'm using Material UI. I want to change the route to /customers/create route and as the result of that route change show the dialog. This means that even if users hit F5 and refresh the page, they would still see the form shown in the dialog.

I can't make it work. I created the nested <Route /> definition:

<Routes>
    <Route path='/customers' element={<Customers />}>
        <Route path='create' element={<CreateCustomer />} />
    </Route>
</Routes>

And I also inserted an <Outlet /> in my Customers.js:

import { Outlet } from 'react-router-dom'

const Customers = () => {
    const [dialogIsShown, setDialogIsShown] = useState(false);
    return <div>
        <Button onClick={() => setDialogIsShown(true)}>Create</Button>
        {* customer creation component is here, inside a dialog *}
        <Dilog open={dialogIsShown}>
            <CreateCustomer />
        </Dialog>
        {* other UI parts *}
        <Outlet />
    </div>
}

And when I click the new button, I use useNavigate to change route. But nothing happens.

I'm stuck here.

Any help is appreciated.

like image 457
Hossein Fallah Avatar asked Feb 01 '26 14:02

Hossein Fallah


1 Answers

I've gathered that you want to click a button in the Customer component to navigate to the "/customers/create" route and render the CreateCustomer component into a Dialog. If this is correct then I believe the following should be close to what you are describing as desired behavior.

import { Outlet, useNavigate } from 'react-router-dom'

const Customers = () => {
  const navigate = useNavigate();

  return (
    <div>
      ... customers list ...

      <Button onClick={() => navigate("create")}>Create</Button>
      <Outlet />
    </div>
  );
}

Render the dialog open by default when the route matches and the element is rendered.

<Routes>
  <Route path='/customers' element={<Customers />}>
    <Route
      path='create'
      element={(
        <Dialog open>
          <CreateCustomer />
        </Dialog>
      )}
    />
  </Route>
</Routes>
like image 138
Drew Reese Avatar answered Feb 04 '26 05:02

Drew Reese