Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router-dom direct access to child path

I have my main route in my main component set like that

<Main>
    <Switch>
        <Route exact path="/login" component={ LoginPage }/>
        <PrivateRoute path="/" component={ PrivatePages }/>
    </Switch>
</Main>

and inside PrivatePages the routes are set like this

<div>
    <Switch>
        <Route exact path="/users/:id" component={ UsersPage }/>
    </Switch>
</div>

when I'm accessing it like http://localhost:3000/users I see the right page (the UsersPage component) and when I click on a user it transfer to http://localhost:3000/users/someUserId (I'm doing it by using <Link>) and it works perfectly fine .. but when I refresh or trying to rich directly to a specific user's page I get a blank page which tries to load http://localhost:3000/users/main.js (I have no idea why it tried to load this file) I guess it's something from react-router-dom I tried to google it but I didn't find anything relevant ... can't put my finger hand on what I'm missing exactly.

thanks.

like image 407
greW Avatar asked Sep 20 '17 15:09

greW


People also ask

How do you redirect in dom on a react router?

The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.

How do I change the default path in react router?

Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!

How do you restrict access to routes in react?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?


1 Answers

Ok, your page is blank because it can't download your main.js file which initializes your React app.

Corresponding to your dev server output-public-path (which is / by default) you should be able to download main.js with the following URL: http://localhost:3000/main.js, but you have http://localhost:3000/users/main.js. This is because you specified src='main.js' for <script> in your html file, which is a relative path. Server takes current URL path (http://localhost:3000/users/) and concatenates it with main.js. And we have http://localhost:3000/users/main.js.

You just need to set your <script> src attribute with an absolute path: src="/main.js".

like image 143
GProst Avatar answered Oct 27 '22 00:10

GProst