React – Django page is blank on refresh

Question:

Hello I am using Django as my backend and React as frontend. I have an issue when I refresh page and I am not on root page '/' the page goes blank. Also If Ill try to go instantly somewhere else then the home page such as /contact it is blank also. I know it is because the backend server was not contacted as it is said here. I tried to fix it with useHistory but it did not work showing useContext error.
What is the best way to fix this issue with Django – React stack?

main urls.py:

    urlpatterns = [
       ...
       path('', TemplateView.as_view(template_name='index.html'))
    ]

app urls.py:

router = routers.DefaultRouter()
router.register('frontpage', FrontpageViewSet, 'frontpage')
router.register('gallery', GalleryViewSet, 'gallery')
urlpatterns = router.urls

React index.js:

import {BrowserRouter} from "react-router-dom";

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </React.StrictMode>,
document.getElementById('root')
);

App.js:

const location = useLocation();
return (
    <div className="App">
        <GlobalStyle/>
        <Nav/>
        <Switch location={location} key={location.pathname}>
            <Route exact path='/'>
                <HomePage/>
            </Route>
            <Route exact path='/gallery'>
                <GalleryPage/>
            </Route>
            <Route exact path='/contact'>
                <ContactPage/>
            </Route>
        </Switch>
    </div>
);
Asked By: pipikej

||

Answers:

I fixed by putting useHistory to all pages and loading it with useEffect when the page loads.

Answered By: pipikej

You can use re_path instead of path in your main urls.py. Don’t forget to import it also:

from django.urls import include, re_path
Answered By: mathsnerd22
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.