2

How do I setup the Django urls.py and the React Components to establish this? My requirement is to have Django render the homepage with urls file as such:

urlpatterns = [
    path('', views.index),
    ]

React router should then render the subsequent links (eg. /home, /about)

2 Answers2

7

To set up a catch-all route with the django 2.0 path syntax, use the <path:> converter. This will route any url to the react app served from views.index.

urlpatterns = [
    path('<path:route>', views.index),
]

For regex routes, an empty string is a catch-all.

urlpatterns = [
    re_path('', views.index),
]

If you have routes that should not be routed to the react app, you must include those routes first.

urlpatterns = [
    path('admin/', admin.site.urls),
    path('<path:route>', views.index),
]
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
  • 1
    I'm using Django 3.1, and `` wouldn't work for me. `` did the trick, though. Does the `route` portion serve some function here that isn't obvious? – Derek Nov 29 '20 at 20:35
  • 1
    @Derek. Thanks for catching that. Actually I got it the wrong way around, and nobody noticed. It should be ``, and I've edited my answer to correct that now. Here "route" is just the name of segment and will be passed to the view function as a keyword argument. The reason why you would use the `path:` converter is to also catch uls that may contain any `/`. If you use only ``, I think it's equivalent to ``. The default `str:` converter does not accept `/`, so it will not be a true catch-all route. – Håken Lid Nov 29 '20 at 23:31
1

Your React application is going to be served from a single page. I'm assuming your view.index is your blank html, which usually looks something like this:

<div id="root"></div> <script src="/dist/bundle.js"></script>.

(make sure your application bundle is being served in the script tag). Django will serve the html file with the route associated. In your case, if you want the root of the application to be React, then your urls.py would look like:

urlpatterns = [ path('/', views.index), ]

Once Django serves up the html file, and the script tag finishes loading your app onto that page - at this point it will enter the root of your React application, and from there React-Router will take over. Django will not be aware of any further routes because once React takes over the routing is 'virtual'. I hope this answers your question - please let me know if you need any further information.

LukeT
  • 340
  • 2
  • 9
  • Was able to get it working :) Any idea on how to get the BrowserHistory in react-router-dom working with a django backend? – Kunal Jagadish Oct 17 '18 at 03:29
  • Nvm, was able to fix it by using HashRouter instead :) – Kunal Jagadish Oct 17 '18 at 03:38
  • Glad you found a solution! For future reference [this](https://stackoverflow.com/questions/42672842/how-to-get-history-on-react-router-v4) is a thread about the browser history object. – LukeT Oct 17 '18 at 16:09