Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react routing and django url conflict

I am using reactjs as a frontend and django as backend. React router is used for routing. When i refresh the page that has routed by react router, i get django 404 Page Not Found error. If i refresh the homepage, i dont get any such error because the homepage is rendered by django template too using its url.

Do i have to configure that in the webpack? My project structure is i have seperated django and reactjs. I have created a folder as frontend where reactjs file resides.

UPDATE

homepage template has all the link for routes like addrestaurant.

my webpack.config file

const path = require("path"); if(!process.env.NODE_ENV) {     process.env.NODE_ENV = 'development'; }  module.exports = {   entry: [     './src/index.js'   ],   output: {     path: path.join("../app/static/build/", "js"),     filename: "app.js",     publicPath: "../app/static/build/"   },   devtoo: 'source-map',   debug: true,   module: {     loaders: [{       exclude: /node_modules/,       loader: 'babel',       query: {         presets: ['react', 'es2015', 'stage-1']       }     },     {test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=images/[name].[ext]"},     ]   },   resolve: {     extensions: ['', '.js', '.jsx']   },   devServer: {     historyApiFallback: true,     contentBase: './'   } }; 

urls.py

urlpatterns = [     url(r'^', views.home, name="homePage"),     url(r'^(?:.*)/?$', views.home), ] 

home.html

{% extends 'base.html' %}  {% block title %} Foodie | Homepage {% endblock title%}  {% block content %}   <div class="homepage">   </div> {% endblock %}  {% block js %}   {{ block.super }}   <script type="text/javascript">   var data = {          isUserAuthenticated:{% if request.user.is_authenticated %}true{% else %}false{% endif %}     };     console.log('data',data);     $(function() {       app.showHomePage(".homepage",data);     });   </script> {% endblock %} 

index.js

window.app = {       showHomePage: function(id,data){           render(             <Provider store={createStoreWithMiddleware(reducers)}>                 <Router>                  <App />                 </Router>             </Provider>, document.querySelector(id)           );       }, } 

Banner is a child component of App component

const Banner = (props) => (    <div className="navbar-container">         <div className="ui container">             <div className="ui large secondary menu">                 <a className="toc item">                     <i className="sidebar icon"></i>                 </a>                 <div className="item logo">                     <div className="ui logo shape">                         <div className="sides">                             <div className="active ui side">                                 Foodie                             </div>                         </div>                     </div>                 </div>                 <Link to="/restaurant" className="active item tab">Home</Link>                 <Link to='/addrestaurant' className='item tab'>Add Restaurant</Link>                 <Link to="/products" className="item tab">Products</Link>                 <div className="right item">                     <a href="" id="bookingInfoButton" className="ui white inverted button">Booking</a>                 </div>             </div>         </div>       </div> );  export default Banner; 
like image 397
milan Avatar asked Nov 27 '16 06:11

milan


People also ask

Can React and Django work together?

React will consume your Django REST API. React will make HTTP requests to your REST API in order to fetch and set data. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page.

Does React router change URL?

The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.

Is using React with Django a good idea?

The advantages of using React with DjangoIt provides an easy way to manage code for both the backend and the frontend. Django can be integrated very quickly with React using static files. The frontend and backend are separately written in Django, making testing, finding and removing bugs easier.


1 Answers

The issue is probably that you haven't configured your URLs to handle the routes that are defined in React Router. In your Django urls.py you should be using a catch all to match all URLs to your index template

urlpatterns += [     # match the root     url(r'^$', base_view),     # match all other pages     url(r'^(?:.*)/?$', base_view), ] 

The base_view would be a view function that renders a template which includes your bundled app.

like image 110
Paul S Avatar answered Sep 18 '22 14:09

Paul S