How to separate routes inside a React App - javascript

I have the following on my index.js
<Router routes={routes} />
I would like to have routes section in a separate file, so far I tried this:
routes.js
export default (
<div>
<Route path="/" component={AppComponent}>
<Route path="/someother" component={AddProductComponent} />
</Route>
<Route path="/products" component={ListProductComponent} />
</div>
);
and in index.js
import routes from './routes';
<Router routes={routes} />
For some reason the app shows blank now. looks like the routes are not rendered.
UPDATE, this is my whole index.js except missing imports due stackoverflow companing about too much code put:
const rootReducer = combineReducers({
products: productReducer,
});
const store = createStore(
rootReducer,
applyMiddleware(thunk),
);
ReactDOM.render(
<Provider store={store}>
<Router routes={routes} />
</Provider>
, document.getElementById('root')
);
Update routes.js
export default (
<Switch>
<Route exact path="/" component={AppComponent}/>
<Route path="/products" component={ListProductComponent}>
<Route path="/details/:productId" component={AddProductComponent} />
</Route>
</Switch>
);

You're missing the switch:
<Switch>
<Route path="/someother" component={AppComponent}>
<Route path="/products" component={ListProductComponent} />
<Route path="/" component={AppComponent}>
</Switch>
Also, your code will only show AppComponent, as any url (/, /home, /etc) starts with the slash you put in the path attribute. You might want that as a last page, a fallback.
The path attribute works with a wildcare: path="/" -> path="/**" are functionally the same. If you want an exact path, add exact to the Route.
If you mean to split routes into seperate files, you can do this:
<Switch>
<Route path={"/user"} component={UserRouter}/>
<Route path={"/product"} component={ProductRouter}/>
</Switch>
// In userRouter.jsx:
export function UserRouter() {
return <Switch>
<Route exact path={"/user/list"} component={UserListPage}/>
<Route exact path={"/user/signup"} component={userSignupPage}/>
<Route exact path={"/user/profile"} component={UserProfilePage}/>
</Switch>
};

Related

Routes - react-router v5 - hitting NotFound always

I am trying to add a Landing page for my application. After the authorization. The routes after landing page is always hitting the NotFound route. I am unable to figure out the reason.
The initial routes are :
const Initial = ({ settings }) => {
const store = setupStore(reducers, { settings });
return (
<Provider store={store}>
<AuthProvider appSettings={settings}>
<Router basename={settings.AppContextPath}>
<MainLayout>
<Switch>
<Route
path={LOGIN_URL}
component={Login}
/>
<Route
path={LOGOUT_URL}
component={Logout}
/>
<Route
exact={true}
path={SILENT_RENEW_URL}
component={SilentRenew}
/>
<AuthenticatedRoute>
<App>
<Switch>
<Route
exact path="/"
component={LandingPage}
/>
<Route component={NotFound} />
</Switch>
</App>
</AuthenticatedRoute>
</Switch>
</MainLayout>
</Router>
</AuthProvider>
</Provider>
);
};
In the LandingPage component I have added rest of the routes which should be based on clicking the Link from Landing Page:
const FeatureRoutes = () => {
return (
<Switch>
<Route
path={`/:Id/feature1`}
component={Feature1}
/>
<Route
path={`/:Id/feature2`}
component={Feature2}
/>
<Route exact path={`/:Id`} component={Features} />
</Switch>
);
};
export default FeatureRoutes;
Clicking the link navigates correctly to url with "/:id", but it shows NotFound page.
Please let me know which part I am doing wrong.
i could solve it to go till 'Features' route by changing the route so :
<AuthProvider appSettings={settings}>
<Router basename={settings.AppContextPath}>
<MainLayout>
<Switch>
Route
path={LOGIN_URL}
component={Login}
/>
<Route
path={LOGOUT_URL}
component={Logout}
/>
<Route
exact={true}
path={SILENT_RENEW_URL}
component={SilentRenew}
/>
<AuthenticatedRoute>
<App>
<Switch>
<Route
exact path="/"
component={LandingPage}
/>
<Route
path={'/:Id'}
component={FeatureRoutes}
/>
</Switch>
</App>
</AuthenticatedRoute>
</Switch>
</MainLayout>
</Router>
</AuthProvider>
</Provider>
);
};
I moved the NotFound route into FeatureRoutes.

React js multiple routes files doesn't work

I am working on one of the project and project has multiples routes aroud 400+ so main routes file was too long.
So I just split the routes code based on the modules and import into the main routes file.
After importing the split route file into the main Routes file routes doesn't work.
Am using 'react-router-dom'
Main File
ReactDOM.render(
<React.Suspense
fallback={<div>Loading</div>}
>
<Switch>
<Route exact path="/"component={Home} />
<UsersRoutes />
<ProductsRoutes />
</Switch>
</React.Suspense>,
document.getElementById('app')
);
UsersRoutes File
<>
<Route exact path="/all-users" component={Component1} />
<Route exact path="/active-users" component={Component2} />
<Route exact path="/deactivated-users" component={Component3} />
...
</>
ProductsRoutes File
<>
<Route exact path="/all-products" component={Component1} />
<Route exact path="/sale-products" component={Component2} />
<Route exact path="/feature-products" component={Component3} />
...
</>
You can try this approach.
UsersRoutes.js
import ...
export default [
{ path: '/all-users', component: Component1},
{ path: '/active-users', component: Component2}
]
And use it like this.
<Switch>
<Route exact path="/"component={Home} />
{ UserRoutes.map(props => <Route {...props} />) }
</Switch>

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 browserHistory.push doesn't redirect

Trying to use browserHistory.push method to change my route programmatically.
It will change the route (per browser address bar) but doesn't update the view.
Here's my code
App.jsx
const AppStart = React.createClass({
render: function() {
return (
<MuiThemeProvider>
<Router history={hashHistory}>
<Route path="/" component={Main}>
<Route path="experiences" component={Experiences} />
<Route path="people" component={Profiles} />
<Route path="login" component={Login} />
<IndexRoute component={Home}/>
</Route>
</Router>
</MuiThemeProvider>
);
}
});
ReactDOM.render(
<AppStart />,
document.getElementById('app')
);
Component:
handleLoginRedirect(e) {
browserHistory.push('/experiences');
},
render() {
return (
<div className='row'>
<div className='col-sm-10 col-sm-offset-1'>
<form role='form'>
<RaisedButton label="Redirect" onClick={this.handleLoginRedirect} />
</form>
</div>
</div>
);
Your router configuration uses hashHistory while you're pushing onto browserHistory.
It's easy to miss something like this and it's understandable.
Replace hashHistory with browserHistory in your Router like so:
<Router history={browserHistory}>
Full Snippet:
const AppStart = React.createClass({
render: function() {
return (
<MuiThemeProvider>
<Router history={browserHistory}>
<Route path="/" component={Main}>
<Route path="experiences" component={Experiences} />
<Route path="people" component={Profiles} />
<Route path="login" component={Login} />
<IndexRoute component={Home}/>
</Route>
</Router>
</MuiThemeProvider>
);
}
});
If you're using the newest react-router api you'll need to use:
this.props.history.push('/path/goes/here');
You may need to bind this to your function when accessing this.props (note: may):
onClick={this.handleLoginRedirect.bind(this)}
Please refer to the following question for all the information on this topic:
Programmatically navigate using react router

using react-router and react-router-redux. when i go to localhost:9000/ it works fine, but not localhost:9000/login

I am wondering what I am doing wrong.
Here's what my router looks like -
const router = (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Content} />
<Route path="/login" component={Login} />
</Route>
</Router>
</Provider>
);
I updated to do what Elod suggested, however I still get the same issue :(
const router = (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Content} />
<Route path="login" component={Footer} />
</Route>
</Router>
</Provider>
);
solution:
app.get('/*', function(req, res) {
res.sendFile(path.resolve(__dirname) + '/index.html');
You already have a parent route of / defined.
There's no need to add the / at the Login component's level. Remove it and leave
<Route path="login" component={Login} />
only. Should do the trick for you.

Categories

Resources