I’m using react-router-dom
. After deployment the app is not working if we refresh the app, throwing an error Not found
, but it works fine in the local environment. This happens for every route.
<Routes>
<Route path="/" exact element= {<Navigate to="/posts" />} />
<Route path="/posts" exact element={<Home />} />
<Route path="/posts/search" exact element={<Home />} />
<Route path="/posts/:id" element={<PostDetails />} />
<Route path="/auth" exact element={ <Auth/>} />
</Routes>
What went wrong and how to fix this. Is it not working because of improper use of react-router-dom
?
3
Answers
Because react-router-dom only maintain clientside routing and not maintain a serverside routing that’s why you need to rewrite your all path to index.html .
Seems like you hosted on render. Here is their doc how to rewrite path: https://render.com/docs/deploy-create-react-app#using-client-side-routing
This error will occur wherever you would try to hit any route separately. The reason behind this is that render looks for file
/posts
which is not present.For your case, you may resolve it by adding redirect/rewrite rules as below:
The same happens to me when I used to host my React application. I used to make _redirects file in the same directory as index.html inside the public folder. And paste the below code:
This works for me.