I was wondering if it's possible to use "indexRedirect" in a route configuration object (so without using JSX).
I tried without success, so I assumed that this isn't supported at the moment, but then my issue (https://github.com/reactjs/react-router/issues/3150) was closed without comment, so I still don't know if it's because the feature is already there but I misuse it, or because this is a unwanted feature.
Thanks in advance. :)
As described in the docs, the equivalent to indexRedirect using a plain configuration object looks like this
const routes = [{
path: '/',
component: App,
indexRoute: { onEnter: (nextState, replace) => replace('/welcome') },
childRoutes: [
{ path: 'welcome', component: Welcome },
{ path: 'about', component: About }
]
}]
Using plain routes config it's a bit more low level API, and there is no point of having special redirect or indexRedirect keys in the routes object. Instead you could use onEnter to accomplish a redirect. Here is how:
import React from 'react'
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router'
const Home = () => <h3>Home</h3>
const About = () => <h3>About</h3>
const routes = [{
path: '/',
component: Home,
onEnter: (nextState, replace) => replace('/about')
}, {
path: '/about',
component: About
}]
render(
<Router history={browserHistory} routes={routes} />,
document.getElementById('root')
);
Edit: added this into docs as well.
I would appreciate the same thing as JGX: working relative paths for this kind of redirecting
Related
In v5 i have such structure
{
path: '/someurl/:id',
exact: true,
render: ({ params }) => (<Redirect to={`/someurl/extraurl/${params.id}`} />),
}
How to refactor this to V6?
react-router-dom v6 no longer has route props, so you'll need to create a new component to gather the "props", or match.params in this case, and render the redirect as a Navigate component.
const MyRedirect = () => {
const { id } = useParams();
return <Navigate to={`/someurl/extraurl/${id}`} replace />;
};
...
{
path: '/someurl/:id',
element: <MyRedirect />,
}
...
<Route path={obj.path} element={obj.element} />
The accepted answer will work but I'll add my solution too, since it's a bit more dynamic. You can set up a function component that will make use of the useParams hook and the generatePath function so your intended destination gets the params from the initial route (whatever they may be):
import React, { FunctionComponent } from 'react';
import { generatePath, Navigate, useParams } from 'react-router-dom';
interface IProps {
to: string;
replace?: boolean;
state?: any;
}
const Redirect: FunctionComponent<IProps> = ({ to, replace, state }) => {
const params = useParams();
const redirectWithParams = generatePath(to, params);
return (
<Navigate to={redirectWithParams} replace={replace} state={state} />
);
};
export default Redirect;
Using this should work with your first example (and any other routes / redirects with dynamic params).
Well, I have been reading, and I can't find a solution for this. I'm starting with this project. I want to know how to use a service with GET method like this https://api.myjson.com/bins/1axhir and use it in my menu. This is how my code is written. I'm using a template NGX-ADMIN but they don't have any documentation.
page.components.ts
import { Component } from '#angular/core';
import { MENU_ITEMS } from './pages-menu';
#Component({
selector: 'ngx-pages',
template: `
<ngx-sample-layout>
<nb-menu [items]="menu"></nb-menu>
<router-outlet></router-outlet>
</ngx-sample-layout>
`,
})
export class PagesComponent {
menu = MENU_ITEMS;
}
pages-menu.ts
import { NbMenuItem } from '#nebular/theme';
export const MENU_ITEMS: NbMenuItem[] = [
{
title: 'Dashboard',
icon: 'nb-home',
link: '/pages/dashboard',
home: true,
},
{
title: 'CONFIGURACIONES',
group: true,
},
{
title: 'Usuarios',
icon: 'nb-keypad',
link: '/pages/ui-features',
children: [
{
title: 'Buttons',
link: '/pages/ui-features/buttons',
},
],
},
];
I want to use a web service like, this example https://api.myjson.com/bins/1axhir, instead of the Constant Array give me a hand please. TY
Angular is only used for FrontEnd and for making API you need to use Node.js or any other Backend framework.
if you want i can give you the node.js code for the same.
Also for integrating the API in angular application, you need to use observeables and subscribers
I'm using Laravel 5.4, vue.js 2.3 and vue-router.
Current situation
When example.com is hit, Laravel returns the app view which starts the Vue.app
web.php
Route::get('/', function () {
return view('app');
});
app.js
const routes = [
{ path: '/', component: App },
];
const app = new Vue({
el: '#app',
router,
data () {
return {}
},
});
App.vue
export default {
...
}
What I'm trying to do
If usa.example.com is typed, I would like the alert() in my App.vue to show usa.
If italy.example.com is typed, I would like the alert() in my App.vue to show italy.
I read the documentation of vue-router but I'm not sure wether it is a Laravel issue, a Vue issue or both.
App.vue
export default {
....
created() {
alert('subdomain is ' + $route.params.subdomain)
}
}
VueRouter doesn't keep track of the subdomain.
But, you can get the subdomain from the location and use that in your component's created method:
created() {
let subdomain = location.hostname.split('.').shift();
alert('subdomain is ' + subdomain);
}
The above code is based off of this answer.
Not sure what is happening here. I have set up my routing and when I go to my first page localhost:8080/ the first route renders as expected. However if I enter into the url in localhost:8080/store the expected route fails and I receive a 404 cannot find (doesnt even fallback to my not found component).
However if I set up a Link to and click the link it will render my store route as expected.
Shouldn't /store render out my StorePicker component regardless if its entered into the URL or selected via a Link to element?
App.js
import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
//Components
import StorePicker from './components/StorePicker.js';
import Main from './components/Main';
import NotFound from './components/NotFound';
const Routes = () => {
return (
<Router>
<div>
<Link to="/store">Store</Link>
<Switch>
<Route path="/" exact component={StorePicker} />
<Route path="/store" component={Main} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
)
}
render(<Routes />, document.querySelector('#container'));
Assuming you're using Webpack. If so, adding a few things to your webpack config should solve the issue. Specifically, output.publicPath = '/' and devServer.historyApiFallback = true.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
I am creating a website for a client that will use strictly client side react-routing script.
Here is a sample of the router ....
import React from 'react';
import { Route } from 'react-router';
import { generateRoute } from '../utils/localized-routes';
export default (
<Route component={ require('../components/APP') }>
{ generateRoute({
paths: ['/', 'audience'],
component: require('../components/Audience')
}) }
{ generateRoute({
paths: ['speaker'],
component: require('../components/Speaker')
}) }
{ generateRoute({
paths: ['board'],
component: require('../components/Board')
}) },
{ generateRoute({
paths: ['questions'],
component: require('../components/parts/AskQuestion')
}) }
<Route path="*" component={ require('../pages/NotFound') } />
</Route>
);
With this being the code for generateRoute:
export function generateRoute({ paths, component }) {
return paths.map(function(path) {
const props = { key: path, path, component };
// Static `onEnter` is defined on
// component, we should pass it to route props
if (component.onEnter) props.onEnter = component.onEnter;
return <Route {...props} />;
});
}
Problem:
While I understand the Links will bypass server navigation and utilize transition to (client side), on page refresh, I get a "Page Cannot Be found".
If I manually put a hash tag before the browser's url input (myexample.com/#speaker), the page appears, but of course I cannot expect the user to do that.
If I must use hash tags to allow client side routing, where do I put them? I put them in the and/or the router, neither work.
Alternatively, can I achieve total client side routing w/o the ugly hash tags? If, so, how do I do it?
I'd much prefer a solution based on #3, but if all else fails I'll take a solution based on #2.
Any ideas?
Thanks in advance.
I could only find a solution using step #2 above and am stuck with hashtags.
import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import createHistory from 'history/lib/createHashHistory'; <-- using this
// import createBrowserHistory from 'history/lib/createBrowserHistory';
const routerProps = {
routes: require('./router/routes'),
history: createHistory({ <--- added this to remove ugly querystring
queryKey: false
}),
createElement: (component, props) => {
return React.createElement(component, { ...props });
}
};
ReactDOM.render(
React.createElement(Router, { ...routerProps }),
document.getElementById('root')
);
Would still like to know how I can remove the hashtags completely with client-side routing.