React-router not matching on valid route - javascript

I cannot get this react router to match on second part of a path no matter what I do.
Express server is returning index.html for any URL match (I'm not getting a GET error on any URL so I assume this is fine)
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
Here are some examples of routes i've tried, which should be valid rules according to react router docs
Example 1 )
<Route path="test">
<IndexRoute component={Home} />
<Route path="/login" component={Login} />
</Route>
OR
<Route path="test">
<IndexRoute component={Home} />
<Route path="/login" component={Login} />
</Route>
http://localhost:3100/test = Success > Returns home component
http://localhost:3100/test/login = Fail > gives me blank screen
Example 2 )
<Route path="/login" component={Login} />
http://localhost:3100/login = Success > Returns login component
Example 3 )
<Route path="/test/login" component={Login} />
OR
<Route path="test/login" component={Login} />
http://localhost:3100/test/login = Fail > gives me blank screen
I'm using version 2.5, Any help would be much appreciated!
** Yarn dump of react router **
react-router#^2.5.0:
version "2.8.1"
resolved "https://registry.yarnpkg.com/react-router/-/react-router-2.8.1.tgz#73e9491f6ceb316d0f779829081863e378ee4ed7"
dependencies:
history "^2.1.2"
hoist-non-react-statics "^1.2.0"
invariant "^2.2.1"
loose-envify "^1.2.0"
warning "^3.0.0"

Try path="login" instead of path="/login" . The slash before path is not needed in nested routes.
<Route path="test/">
<IndexRoute component={Home} />
<Route path="login" component={Login} />
</Route>

From express documentation, app.get('/*' uses regular expression. so, '/*' work for 0 to n '/'. Try:
app.get('/.*
/.* should resolve '/' + 0 to n caractères.
Regards

I think the problem lies more with the way you are rendering your app than react-router itself, since you are not getting a route not found message but a blank screen, I suggest the following.
when you create your history object do the following
import { useRouterHistory } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
// ========================================================
// Browser History Setup
// ========================================================
const createHistory = (basename) => {
return useRouterHistory(createBrowserHistory)({
basename: basename
})
}
const history = createHistory('/test');
Your route configuration will then look like this
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="login" component={Login} />
</Route>
Your App component would then look something like this
export const App extends Component = {
render() {
return(
<div class='app-container'>
{this.props.children}
</div>
)
}
}
App.propTypes = {
children: PropTypes.element.isRequired
}
export default App;
You'll then be able to access and render the component Login # /test/login

Related

React Router v6 always render "/"

I'm trying to implement router in react-create-app but it always render "/" and showing Home or SignIn page. How can I solve this?
function AppRouter({ isLoggedIn, user }) {
return(
<Router>
<Routes>
<Route path="/profile" element={<Profile />} />
<Route path="/signUp" element={<SignUp />} />
{isLoggedIn
? <Route exact path={"/"} element={<Home user={user}/>} />
: <Route exact path={"/"} element={<SignIn />} />
}
</Routes>
</Router>
)
}
It seems you have a slight misunderstanding of how the HashRouter works with the UI.
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import Profile from "./Profile";
import SignUp from "./SignUp";
import Home from "./Home";
export default function App() {
return (
<Router>
<Routes>
<Route path="/profile" element={<Profile />} />
<Route path="/signUp" element={<SignUp />} />
<Route path="/" element={<Home />} />
</Routes>
</Router>
);
}
The HashRouter handles routing with a URL hash value, i.e. everything after the "#" in the URL. If you are trying to render your app and access "<domain>/" instead of "<domain>/#/" the routing won't work.
For example in your running codesandbox demo, the base URL is "https://5p7hff.csb.app/". At this base URL the hash router isn't really working, and you should really be accessing "https://5p7hff.csb.app/#/" instead so the hash router is loaded and the app's internal routing can work.
From "https://5p7hff.csb.app/#/" you should be to then navigate to any of your routes, i.e. "https://5p7hff.csb.app/#/profile" and https://5p7hff.csb.app/#/signUp".
If you switch to a different router, like the BrowserRouter then the "/#/" is no longer used, the router and routes render from "/" where the app is running from. The routes would be "https://5p7hff.csb.app/", "https://5p7hff.csb.app/profile", and "https://5p7hff.csb.app/signUp".

React Router v6 warning on nested index routes

The following code (codesandbox) produces this warning when the root url is navigated to:
You rendered descendant (or called useRoutes()) at "/" (under <Route path="">) but the parent route path has no trailing "*"...
However, no warning is issued if I navigate to "/post/blah".
import { Routes, Route} from "react-router-dom";
const StreamPage = () => (
<>
<Routes>
<Route index element={<div /> } />
<Route path="post/:subslug/*" element={<div /> }/>
</Routes>
<Routes>
<Route index element={<div />} />
<Route path="post/:subslug/*" element={<div />} />
</Routes>
</>
)
export const App = () => (
<Routes>
<Route path="/" >
<Route path="post/*" element={<StreamPage />} />
<Route index element={<StreamPage />} />
</Route>
</Routes>
)
I know, I could fix the code by merging the two Routes blocks in StreamPage but I'm asking if this is expected behavior and if so what part of the react-router usage contract/API I'm violating? For instance, am I not allowed to have don't have sibling index routes under an index route? If I don't understand when/why this warning is produced I won't be able to avoid it in the future.
(related to this earlier question)

Nested <Route> components are not rendering properly in react-redux-router [duplicate]

I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
main.js
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like
<Route path="/home/dashboard" component={Dashboard}
or even better
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}

React-Router can't make subroutes

Maybe somebody know why I can create subroutes
My code.
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Main} >
<IndexRoute component={Home} />
<Route path="performance" component={Performance} />
<Route path="home" component={Home} >
<Route path="alert" component={Performance} />
</Route>
</Route>
</Router>
</Provider>
// ...
// imports
import Main from './Main'
import Performance from './performance/PerformanceComponent'
import Home from './home/HomeComponent'
import {Router, Route, IndexRoute} from 'react-router'
import {Provider} from 'react-redux'
I can't go to this address -> /home/alert
And Have this errors in console
alert:11 GET http://0.0.0.0:3001/home/css/style.css
alert:12 GET ...home/css/home.css
alert:13 GET ...home/css/detailsView.css
alert:26 GET ...home/bundle.tvc.js
I mean if I write wrong address I have special error
Warning: [react-router] Location "/homealert" did not match any routes
I don't have any idea how should I fix it. Thank you in advance!
You want this if you want to Performance component to render on /home/alert. You need to specify the complete path on each matching Routes.
<Route path="/" component={Main} >
<IndexRoute component={Home} />
<Route path="/performance" component={Performance} />
<Route path="/home" component={Home} >
<Route path="/home/alert" component={Performance} />
</Route>
</Route>
Nesting routes applies to components, not paths. Your app will render as below for /home/alert:
<Main>
<Home>
<Performance>

React router get currently active segment as param

I have following router configuration
<Router history={history}>
<Route path="/" component={ReviewWizard}>
<IndexRoute component={Administrative}/>
<Route path="Administrative" component=Administrative}>
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>
</Route>
<Route path="Offense" component={Offense}/>
</Route>
</Router>
I'm trying to get currently active route segment (ie Administrative or Offense).
Is there a way to do something like this? ie route constraints
<Router history={history}>
<Route path="/:segment" component={ReviewWizard}>
<IndexRoute component={Administrative}/>
<Route path="/:segment=Administrative/:itemId" component={Administrative}>
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>
</Route>
<Route path="/:segment=Offense" component={Offense}/>
</Route>
</Router>
If not, what is best practice to get the current active route segment? I don't like this.context.router.routes[1].path
First off I would recommend the following router config, as it seems that it's what you're aiming for:
<Router history={history}>
<Route path="/" component={ReviewWizard}>
<!-- whenever we hit '/' we redirect to '/Administrative' -->
<IndexRedirect path="/Administrative"/>
<!-- Renders ReviewWizard <- Administrative -->
<Route path="/Administrative" component={Administrative}>
<!-- Renders ReviewWizard <- Administrative <- AdministrativeItem -->
<Route path="/Administrative/:itemId" component={AdministrativeItem}/>
</Route>
<!-- Renders ReviewWizard <- Offense -->
<Route path="/Offense" component={Offense}/>
</Route>
</Router>
As for detecting the currently active route (or if a route fragment is active), I would recommend using the router.isActive -method. Simply do something like this:
if (router.isActive('/Administrative')) {
doSomething()
} else if (router.isActive('/Offense')) {
doSomethingElse()
}
For something more declarative, I recommend just using the location object that react-router injects into each component it manages:
const { location: { pathname } } = this.props
const [ activeSegment ] = pathname.slice(1).split('/')
Hope these help!

Categories

Resources