JaiHind
JaiHind

Reputation: 13

React router dom v-6 not working on build version

I'm working on a chat application that has some paths like below

            <Routes>
                <Route path="/" element={<WelcomeScreen />} />
                <Route path="channels" element={<Home />} />
                <Route path="channels/:id" element={<Home />} />
                <Route path="*" element={<Navigate replace to="/" />} />
            </Routes>

Once the users are authenticated, they are redirected from welcome screen to home page that has all the chats which is on /channels. So if a user were to access /channels or in the case of 404, I redirected to the / path.

Everything works fine when I run it on localhost but once I host it on netlify and when I refresh at /channels instead of redirecting I get a 404 message and <Route path="*" element={<Navigate replace to="/" />} /> Doesn't work.

Can someone tell me what's the problem? Any help would be appreciated.

Upvotes: 1

Views: 2731

Answers (2)

Baalberith
Baalberith

Reputation: 11

you have different solutions, one of them is to put the following in the htaccess:

<ifModule mod_rewrite.c>
RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^c(.*) index.html [NC,L]
</ifModule>

If you still get an error, put your real url in the homepage:"", of your package.json, example: https://wildreds.es/, so the browserRouter will be able to detect you well, take care crack.

Upvotes: 0

Kritish Bhattarai
Kritish Bhattarai

Reputation: 1661

Change your <BrowserRouter> to <HashRouter>. It lets refreshing individual page without 404 error.

Reference: https://reactrouter.com/docs/en/v6/api#reference

Update

If you are using Netlify you can do this to be able to use <BrowserRouter> and avoid hash # in the routes

Create a file named _redirects with following content in your build folder

/* /index.html 200    

Upvotes: 2

Related Questions