How to remove unhandled path URL from ReactJS - reactjs

Disclaimer: I'm pretty sure this is a duplicate, because there's no way no one asked this, but I don't know if i searched the wrong terms or so but I couldn't find an answer, so I'll ask here.
I'm using React routers (react-router-dom), so for example if I set:
<Route path='/home' component={Home} />
At this point, obviously, if I go to localhost:3000/home it will load my homepage, right?
But if I go to localhost:3000/fjnisodjuhfosij (just random text) it will load anyway a blank page, it won't say something like "this page doesn't exist" or just redirecting to the home.
How can I handle this? Thank you

Just add Route with path '*':
<Route path='*' component={YourComponent} />

To direct to home: Add this as the last route in switch: <Route><Redirect to="/home"/></Route>
Or, to show a 404 error page: Create a component for the error page (NotFound lets say) and add it as the last route: <Route component={NotFound} />

Related

React react-router-dom question how to have "/" treated as a string in the url route

I am trying to have URLs be unique identifiers in my route. This requires "/" be treated as strings somehow. I was wondering if someone knew how this could be done?
Here is an example of the code.
<Routes>
<Route path=":url" element={<UrlPage />}} />
</Routes>
So lets say we go to www.website.com/https://stackoverflow.com/questions/ask
I would want "https://stackoverflow.com/questions/ask" to be the URL. How do I get the entire "https://stackoverflow.com/questions/ask" to be treated as string by react router.
Update:
The following will treat everything a string but if a URL has a ? everything to the right will be ignored.
<Routes>
<Route path="*" element={<UrlPage />}} />
</Routes>
This isn't a good idea in general - not only will you have to set this up serverside to deploy this somewhere, but URLs containing / shouldn't be used as subdirectories.
If you really need to, I would URL-encode the address first like this:
www.website.com/https%3A%2F%2Fstackoverflow.com%2Fquestions%2Fask

How do I make a url contain multiple sections? React

So full disclosure, I'm not sure how to ask this question properly, but I do have a decent example. I'm making a React app and I'm trying to make the url more "descriptive" I suppose.
So it starts off at Home, then I go to a Products page and the url changes from /home to /products. This part is fine.
When I want to go to a specific product from the product page, I want the url to change to /products/example instead of just /example. Do I have to specify this with the Links or is there some cleaner way to get it done?
Right now my only answer is to make the link go to /product/example and have the App.js route to the same url. I'm not sure how to properly ask this question for a Google search so I had to ask it here. If you have an idea how to specifically phrase what I'm asking, I'd appreciate that too.
Thanks in advance.
I believe the example in your URL /products/example is the product name for your product. If so, this can be done in putting the product name as an URL parameter using react-router or react-router-dom if you still have not.
by declaring the route as
import { Switch, Route } from "react-router-dom";
const Router = () => (
<Switch>
<Route exact path="/home" component={()=>return <h1>Home</h1>} />
<Route exact path="/products" component={()=>return <h1>Products</h1>} />
<Route path="/products/:productName" component={props=>return <h1>props.match.params.productName</h1>} />
</Switch>
);
export default Router;
more on that here

Adding component to page when more specific route is used

What I'm trying to do is to display User details next to the table of users.
The user table is displayed on /users route and when I go to /users/0 I want to display both, the user table, and component User with the user's details.
Here is what I tried to do: https://codesandbox.io/embed/react-router-redirects-typescript-fg8yf
This, however, displays only a blank page when I try to navigate to the user's details.
Can anyone explain to me what I'm doing wrong, please?
You have provided exact prop here,
<Route exact path="/users" component={Users} />
When you provide exact prop, it will only match the path /users and not anything else. So when you give path /users/0 it will not navigate, because there is no matching Route present.
You need to remove the exact prop,
<Route path="/users" component={Users} />
Read more about exact prop.

React Router, 2 routes with similar urls

I have the following 2 routes:
<RouteEx path="/:id" component={Page2} />
<RouteEx path="/imprint" component={Imprint} />
Every time I click on imprint to navigate to my imprint page, I get an error in my console from Page2 component. How do I prevent calling Page2 when I want to navigate to Imprint page?
The "Route Matching" section of the React-Router documentation provides some tools for dealing with routes that can both serve as matches to the address text. The first is <Switch>, which makes it so that only one route--the first match, even if there are many--responds to the route match. Another is the exact property, which guarantees that a route won't be flexibly interpreted. In your case, you might use them both (though I think the exact tag may not be necessary in your case):
<Switch>
<RouteEx exact path="/imprint" component={Imprint} />
<RouteEx path="/:id" component={Page2} />
</Switch>
In this configuration, if the route matches '/imprint', it will not trigger the '/:id' route. This will work even if the id is a string. (Naturally, you'd have to make sure that you never encounter the case id === 'imprint'.)
If id is a number, then you can try using Regex :
<RouteEx exact path="/:id(\d+)" component={Page2}/>
<RouteEx exact path="/imprint" component={Imprint}/>

How does OKCupid, Reddit handle user profile routing with react router?

I am trying to set up a similar structure, where /profile takes you to your profile and allows you to edit your info. /profile/:userId will take you to someone else's profile, and allow you to send messages but not edit (obviously). I am thinking something similar to this logic:
<Route path='profile'>
<IndexRoute component={requireAuth(Profile)} />
<Route path=':userId' component={requireAuth(Profile)} />
</Route>
and in the Profile component, do something like
if (this.props.params.userId !== this.props.currentUser.id)
<SendMessage toUser={this.props.params.userId} />
This gets cumbersome as there will be a ton of validation checks for pretty much every element on the page whether it's the current user or another profile. Is there a 'correct' way to do this?
Yes. The components for your own profile page (/profile) and the others page (/profile/:userId) should be different components (with maybe similar markup). The component for /profile for example need not have the <SendMessage/> etc.
<Route path='profile' onEnter={requireAuth}>
<IndexRoute component={ProfileSelfComponent} />
<Route path=':userId' component={ProfileOtherComponent} />
</Route>
The requireAuth will handle whether the user is logged in etc.
The only thing you want is that when a user tries to navigate to his own /profile/:profileId it routes back to his own profile
This can be done by adding something like this to the ProfileOtherComponent
componentWillMount(){
if (this.props.params.userId === this.props.currentUser.id)
browserHistory.push('/profile')
}

Resources