How do I render this object in React with React Router? - reactjs

How do I render this object using react router? I want to render this object in a menu.
{main: 'Main', about: 'About', contacts: 'Contacts', '404': 404}

Refactor it this way:
const menu = [
{ title: 'Main', path: '/main' },
{ title: 'About', path: '/about' },
{ title: 'Contacts', path: '/contacts' },
{ title: '404', path: '/404' }
];
Now do this in your JSX wherever you want your menu:
{menu.map(item => <Link to={item.path} alt={item.title} />)}
Don't forget to import Link:
import { Link } from 'react-router-dom'

Related

React implement routes from array programitically

I have a file called routes.js there I import components and create a routes array.
routes.js
import Country from '../src/components/country/Country';
import Countries from '../src/components/country/CountriesList';
import User from '../src/components/user/User';
import UsersList from '../src/components/user/UsersList';
export const routes = [
{
name: 'USER',
children: [
{
name: 'Create',
path: '/user-create',
component: User,
// isHidden: true,
},
{
name: 'Update',
path: '/update-user',
isHidden: true,
component: User,
},
{
name: 'View',
path: '/users',
component: UsersList,
// isHidden: true,
},
],
},
{
name: 'COUNTRY',
children: [
{
name: 'Create',
path: '/country',
component: Country,
},
{
name: 'View',
path: '/countries',
component: Countries,
},
],
},
],
},
];
Then, I want to import that routes array and render routes programmatically.
I did this.
{routes.map(
{children}=>
children.forEach({component,path} => <Route component={component} exact path={path}/>)
)}
This gives me a syntax error.
I think this is because I am trying to render with a ForEach loop.
How do I fix this syntax problem?
You can use the Array#flatMap and Array#map function which will return an array of components which React can render.
{routes.flatMap(items => items.children).map(({ component, path }) => <Route component={component} exact path={path}/>)}
You were also missing some parens () around the curly braces which caused the Syntax error.
E.g. in the following part, you are trying to destructure the object containing the children property. However, you will need to wrap the destructing syntax with parens if you use this in an arrow functions.
{routes.map({children} =>

how to use icon in Ant-design/icons with V4

I have tried to make a menu, so i create a menuList to config the menu with getMenuNodes(), but Ant framework has been upgraded from v3 to v4 which the icon method has been changed. they are now using icon={<PieChartOutlined />} to instead of icon='PieChartOutlined', everything is working well, the icon area shows the word <PieChartOutlined />right now. i do not know why it happened, please help me to solve this problem.
left-navigation.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import logo from '../../assets/images/logo.png';
import './index.less';
import { Menu } from 'antd';
import { PieChartOutlined } from '#ant-design/icons';
import menuList from '../../config/menuConfig';
const { SubMenu } = Menu;
export default class LeftNav extends Component {
getMenuNodes = menuList => {
return menuList.map(item => {
if (!item.children) {
return (
<Menu.Item key={item.key} icon={item.icon}>
<Link to={item.key}>{item.title}</Link>
</Menu.Item>
);
} else {
return (
<SubMenu key={item.key} icon={item.icon} title={item.title}>
{this.getMenuNodes(item.children)}
</SubMenu>
);
}
});
};
render() {
return (
<div className="left-nav">
<Link to="./" className="left-nav-header">
<img src={logo} alt="" />
<h1>Backend System</h1>
</Link>
<Menu
mode="inline"
theme="dark"
>
{this.getMenuNodes(menuList)}
</Menu>
</div>
);
}
}
menuList.js
const menuList = [
{
title: 'Home',
key: '/home',
icon: '<PieChartOutlined />',
},
{
title: 'Item',
key: '/products',
icon: '<PieChartOutlined />',
children: [
{
title: 'Category Control',
key: '/category',
icon: '<PieChartOutlined />',
},
{
title: 'Product Control',
key: '/product',
icon: '<PieChartOutlined />',
},
],
},
{
title: 'User Control',
key: '/user',
icon: '<PieChartOutlined />',
},
{
title: 'Role Control',
key: '/role',
icon: '<PieChartOutlined />',
},
{
title: 'Diagram',
key: '/charts',
icon: '<PieChartOutlined />',
children: [
{
title: 'Bar',
key: '/charts/bar',
icon: '<PieChartOutlined />',
},
{
title: 'Line',
key: '/charts/line',
icon: '<PieChartOutlined />',
},
{
title: 'Pie',
key: '/charts/pie',
icon: '<PieChartOutlined />',
},
],
},
];
export default menuList;
You are passing a string of '<PieChartOutlined />', you need to pass the component directly.
import { PieChartOutlined } from '#ant-design/icons';
and:
{
title: 'Product Control',
key: '/product',
icon: <PieChartOutlined />,
},
You'll need to install ant-design/icons if you haven't already:
npm install --save #ant-design/icons
Since reason performance on the previous version, antd team was apply tree-shaking to use icon. More detail, you can check https://ant.design/docs/react/migration-v4

Angular Router nested named outlets

I'm using Angular (v2.4.5). Is it possible to have nested named outlets?
Here is my situation:
//app.component.html
<router-outlet name="test"></router-outlet>
<router-outlet></router-outlet>
//dashboard.component.html
<router-outlet name="test"></router-outlet>
<router-outlet></router-outlet>
Routes:
const routes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
},
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard],
children: [
{
path: '',
redirectTo: 'inbox',
pathMatch: 'full'
},
{
path: 'inbox',
component: InboxContentComponent
},
{
path: 'test',
component: TestComponent,
outlet: 'test'
}
],
{
path: 'test',
component: TestComponent,
outlet: 'test'
}
}
If I go to this url: http://localhost/login(test:test) the TestComponent is loaded in the app.component.html outlet.
If I go to this url: http://localhost/dashboard/inbox(test:test) the TestComponent is loaded in the app.component.html outlet and not in dashboard.component.html
I want to be able to target test outlet from dashboard. Is it possible?

Angular 2 routing issue

Can somebody help me with angular 2 routing.
I have 2 pages.. home and search results page..
Header for home and search results page are different..
here is my code, I am able to display the home page with header but when I go to search results page, header is not getting replaced with new one..
home.routes
export const HomeRoutes: Routes = [
{ path: '', component: HomeComponent},
{ path: '', component: HomeHeadbarComponent, outlet: 'route1' }
];
search.routes
export const SearchRoutes: Routes = [
{ path: 'search', component: SearchPanelComponent},
{ path: 'search', component: HeadbarComponent, outlet: 'route1' }
];
App.html
<router-outlet name="route1"></router-outlet>
<router-outlet></router-outlet>
Appreciate your help
Your home.routes should be below code this will be redirect to you HomeComponent and if you want to redirect it on SearchPanelComponent both you can use in below code
import { Routes, RouterModule } from '#angular/router';
import { HomeComponent} from './Home';
export const routes: Routes = [
{ path: '', redirectTo: 'Home', pathMatch: 'full' },
{ path: 'Home', component: HomeComponent},
{ path: 'search', component: SearchPanelComponent},
];
export const appRoutingProviders: any[] = [
];
export const routing = RouterModule.forRoot(routes);
I assume, that happens because you have empty path path: '' for the first header, so it could overlap the new one. Could you try with the different path, and check it out, should help.
got it working with the code below..
{
path: 'search',
children: [
{
path: '',
component: SearchPanelComponent
},
{
path: '',
component: HeadbarComponent,
outlet: 'route1'
}]
}

RC5 Angular2 route default component

I have existing PHP website, which I start adding angular2 component to.
I have added router script, to help load different component by its url.
When I navigate away from the component page, I get following error Error: Uncaught (in promise): Error: Cannot match any routes: 'dashboard'
I understand, that I need to create another component to make this error disappear. But I don't want to create another component, because there are so many pages, I would end up creating component for each page.
So I wanted to ask, how to make 1 default component, which will pickup if no component was available OR how can I just make this error disappear, so it does not trigger if it cant found any router or component for that path.
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import {TestComponent} from "./test/test.component";
const appRoutes: Routes = [
{ path: 'search', component: TestComponent }
];
export const appRoutingProviders: any[] = [
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
you may add a wildcard route which will redirect to a default component if route does not match.
{ path: 'default', component: DefaultComponent },
{ path: '**', redirectTo: '/default' }
So if the route does not match your default component will be loaded in the router outlet.
Hope this helps!!
I use this as default route:
{ path: '', component: Home, text: 'Home' }
and this is my full routes:
export const routes: TextRoute[] = [
{ path: '', component: Home, text: 'Home' },
{ path: 'accordion', component: AccordionDemo, text: 'Accordion' },
{ path: 'alert', component: AlertDemo, text: 'Alert' },
{ path: 'buttons', component: ButtonsDemo, text: 'Buttons' },
{ path: 'carousel', component: CarouselDemo, text: 'Carousel' },
{ path: 'collapse', component: CollapseDemo, text: 'Collapse' },
{ path: 'dropdown', component: DropdownDemo, text: 'Dropdown' },
{ path: 'pagination', component: PaginationDemo, text: 'Pagination' },
{ path: 'popover', component: PopoverDemo, text: 'Popover' },
{ path: 'progressbar', component: ProgressbarDemo, text: 'Progressbar' },
{ path: 'rating', component: RatingDemo, text: 'Rating' }
];
export const AppRoutes = RouterModule.forRoot(routes, { useHash: true });
Check out my learning angular2 project at github, stars are welcome.
Im too new to comment, my question is if you are using express backend? app.use() might be able to save you some trouble. instead of declaring the routes try in app.js
var routes = require('routes');
app.use('/name-of-url', routes )
then in routes
router.get('name-of-url', function(res,req,next){
res.sendFile(path to php file to serve)
})
You may also need to change your express templating engine to php, not entirely sure.

Resources