[Django]-Configuring React Routes, Django URLs using Webpack

4👍

If I understand your question correctly, then views.html renders the page that will run the app defined in App.js. And the problem you have is that if you go to a URL http://yourserver/my-quiz, where my-quiz is a quiz name, the request will be sent to the Django server, which says: 404, I don’t know about that URL.

One working solution is to add a catch-all route to your Django main app:

urlpatterns += re_path(r'.*', views.index)

as the last route. This simply makes Django render your app for each and every request, and react-router will take care of the routing.

The downside to this is that you won’t get a 404 if the page really doesn’t exist (in your case, there is no quiz by that name). I haven’t found a solution for that yet except duplicating routing configuration (in your case, checking in the Django app if a quiz with that name exists).

👤fqxp

0👍

usually in the frontend framework like (angular, react, vue ) the routers only handle te calls in (the client side) and draw the correct component for each route so you need a component that works like a service, and there make calls to the backend api. e.j.

utility.js

export function get_some_route(){
    return fetch('some_route');
}

the utility file contain functions to fetch the backend routes. so you can
import this file an get the data in the component rendered for the router.

your_component.js

import get_some_route from 'utility.js';
class x extends component{
  ...
  componentDidMount(){
     get_some_route().then(response => {
         // do some thing with the data e.j
         this.setState({data: response.data});
     }
  }
  ...
  render(){
      return(/*some html with the data */);
  }
}
👤Gytree

0👍

I had a simmilar issue but for me the django admin page was not showing. Adding this to my frontend/urls worked for me.

urlpatterns += re_path(r'^.*/$', views.index)

Leave a comment