Wapgee Logowapgee
React

React: forget useState, use router for modals

When you think about handling modals in React, you probably think about handling them in the state. That's what the majority of the devs are doing. You usually use st

Afaq Karim
Apr 25, 2021 · 1 min read
React: forget useState, use router for modals
React: forget useState, use router for modals

When you think about handling modals in React, you probably think about handling them in the state. That's what the majority of the devs are doing. You usually use state from React.useState to control them.

As our title describes, let's handle those modals through routes. When you are on route /create-user, The model create will open, and if you are on route /user/12/edit The edit modal will be opened. We will render those modals on the same user's page, But the prop will change, If you are on the edit page, The edit prop will pass true and the same goes for creating user page.

Now, let's setup routes

On lines 37, 40, and 43. You will observe we have used the same component for showing users but changed props that show modals.

Complete demo and code at https://codesandbox.io/s/wandering-fog-5wc22. If you open the complete demo, you will observe how the URL changes when you open or close the modals.

#react#routes#modals#antdesign#javascript
Written by
Afaq Karim

Hard-working listing programmer with a flair for creating elegant solutions in the least amount of time. As a freelance programmer and web developer created SASS software for local clients and international clients as well. CTO at @wapgee

Comments

Sign in to join the conversation.

Loading comments…

More from Afaq Karim

All posts →