Handling sidebar open-close state while navigating to links React - javascript

In my react application, I have added a sidebar window for the mobile view. Inside the sidebar, I have few links that navigates to certain pages like contact-us, about-us, etc. accordingly.
It looks like this:
As per my requirement, when clicking on any of the links, the sidebar state sets to false, causing the sidebar to be closed and rendering the page navigated using the link.
But I am facing issues such that whenever I click any of the links below, the page related to that link renders (i.e. it navigates to the page in the background), but the sidebar does not close, even though its state is updated every time as required. The sidebar remains open.
This is the code snippet:
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
const SideDrawer = () => {
const navigate = useNavigate();
const [openDrawer, setOpenDrawer] = useState(false);
const [usefulLinks] = useState([
{
link_name: "About Us",
path: "/about-us",
},
{
link_name: "Contact Us",
path: "/contact-us",
},
{
link_name: "Privacy Policy",
path: "/privacy-policy",
},
{
link_name: "Terms and Conditions",
path: "/terms-and-conditions",
},
]);
const handleSideBar = (e, path) => {
e.preventDefault();
setOpenDrawer(false);
navigate(`${path}`);
};
return (
<>
<Drawer open={openDrawer} onClose={() => setOpenDrawer(false)}>
<Grid container direction="column" style={{ flexGrow: 1 }}>
<Grid
item
style={{
marginTop: "auto",
}}>
<List>
{usefulLinks.map(({ path, link_name }, id) => {
return (
<ListItem key={id} onClick={(e) => handleSideBar(e, path)}>
{link_name}
</ListItem>
);
})}
</List>
</Grid>
</Grid>
</Drawer>
<IconButton
onClick={() => setOpenDrawer(!openDrawer)}
className={classes.icon}>
<MenuIcon fontSize="large" />
</IconButton>
</>
);
}
export default SideDrawer;
I am using MUI's List for element rendering.
There might be a minor issue that I'm unable to figure out, any help to resolve the same will be appreciated!
Thanks in advance.

Related

Warning: Each child in a list should have a unique "key" prop. how to fix this?

Ive been using this project with out a problem and now all of a sudden I keep getting this error and it won't show my notes when I click on the my notes section. What do I have to do for it to go away. The backend is up and running and I can see the static data but it wont show on the app
import { makeStyles } from '#mui/styles'
import React from 'react'
import { Drawer } from '#mui/material'
import { Typography } from '#mui/material'
import List from '#mui/material/List'
import ListItem from '#mui/material/ListItem'
import ListItemIcon from '#mui/material/ListItemIcon'
import ListItemText from '#mui/material/ListItemText'
import { AddCircleOutlineOutlined, SubjectOutlined } from '#mui/icons-material'
import { useHistory, useLocation } from 'react-router-dom'
import AppBar from '#mui/material/AppBar'
import Toolbar from '#mui/material/Toolbar'
import { format } from 'date-fns'
import { red } from '#mui/material/colors'
const drawerWidth = 240 // 500 - subtract this number from
const useStyles = makeStyles((theme) => {
return{
page: {
background: '#E5E4E2',
width: '100%',
padding: theme.spacing(3)
},
drawer: {
width: drawerWidth
},
drawerPaper: {
width: drawerWidth
},
root: {
display: 'flex' //places the drawer side by side with the page content
},
active: {
background: '#E5E4E2'
},
// title:{
// padding: theme.spacing(13),
// alignItems: 'center'
// },
}})
export default function Layout({ children }) {
const classes = useStyles()
const history = useHistory()
const location = useLocation()
const menuItems = [
{
text: 'My Projects',
icon: <SubjectOutlined color="secondary" />,
path: '/'
},
{
text: 'Create Project',
icon: <AddCircleOutlineOutlined color="secondary" />,
path: '/create'
}
]
return (
<div className={classes.root}>
{/* side drawer */}
<Drawer
className={classes.drawer}
variant='permanent' //Lets MUI know we want it on the page permanently
anchor="left" // position of drawer
classes={{ paper: classes.drawerPaper}}
>
<div>
<Typography variant="h5" sx={{textAlign: 'center'}}>
Projects
</Typography>
</div>
{/* List / Links */}
<List>
{menuItems.map(item => (
<div className={location.pathname == item.path ? classes.active : null}>
<ListItem key={item.text} button onClick={() => history.push(item.path)}>
<ListItemIcon>{item.icon}</ListItemIcon>
<ListItemText primary={item.text} />
</ListItem>
</div>
))}
</List>
</Drawer>
<div className={classes.page}>
<div className={classes.toolbar}></div>
{children}
</div>
</div>
)
}
enter image description here
Updated
I'm sorry, of course, you should just move key to the parent div. I didn't notice it. Chris who answered in the comments is right and my answer was not needed. I rewrote the answer.
To have an unique key use index in map or like you did item.text if text is unique for each element in map.
menuItems.map((item,index) =>
The idea is that map has to contain unique key for each element.
In result we have:
<div key={item.text} className={location.pathname == item.path ? classes.active : null}>
or
<div key={index} className={location.pathname == item.path ? classes.active : null}>
And you need to remove key from the List.
Hope this helps! Regards,

Resetting screen to first Parent screen, from a nested screen (React navigation & React Native)

I've followed the documentation for creating bottom tab navigation with react-navigation v5 ("#react-navigation/native": "^5.2.3")
Currently is partially used this example in my project from docs https://reactnavigation.org/docs/bottom-tab-navigator/ to fit the needs of version 5.
Example might be following
// Navigation.tsx
import { BottomTabBarProps } from '#react-navigation/bottom-tabs';
import { TabActions } from '#react-navigation/native';
import * as React from 'react';
function Navigation({ state, descriptors, navigation }: BottomTabBarProps) {
return (
<View>
{state.routes.map((route, index) => {
const { options } = descriptors[route.key];
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
const jumpToAction = TabActions.jumpTo(options.title || 'Home');
navigation.dispatch(jumpToAction);
}
};
return (
<TouchableOpacity
key={options.title}
accessibilityLabel={options.tabBarAccessibilityLabel}
accessibilityRole="button"
active={isFocused}
activeOpacity={1}
testID={options.tabBarTestID}
onPress={onPress}
>
{route.name}
</TouchableOpacity>
);
})}
</View>
);
}
export default Navigation;
However, I have a couple of nested StackNavigators as described in AppNavigator.tsx
AppNavigator.tsx
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import React from 'react';
import { AppState, AppStateStatus } from 'react-native';
import Navigation from '../components/navigation/Navigation';
import AccountScreen from '../screens/account';
import SettingsScreen from '../screens/settings';
import SupportScreen from '../screens/support';
import HomeNavigator from './HomeNavigator';
import TransactionNavigator from './TransactionNavigator';
const { Navigator, Screen } = createBottomTabNavigator();
const AppNavigator = () => {
return (
<View>
<Navigator tabBar={(props) => <Navigation {...props} />}>
<Screen
component={HomeNavigator}
name="Home"
options={{ title: 'Home' }}
/>
<Screen
component={TransactionNavigator}
name="Transactions"
options={{
title: 'Transactions' }}
/>
<Screen
component={AccountScreen}
name="Account"
options={{ title: 'Account' }}
/>
<Screen
component={SupportScreen}
name="Support"
options={{ title: 'Support' }}
/>
<Screen
component={SettingsScreen}
name="Settings"
options={{
title: 'Settings' }}
/>
</Navigator>
</View>
);
};
export default AppNavigator;
And I am aiming for resetting the nested StackNavigator each time user leaves it. So example can be HOME -> TRANSACTIONS -> TRANSACTION_DETAIL (which is part of a nested navigator) -> HOME -> TRANSACTIONS
currently, I see a TRANSACTION_DETAIL after the last step of the "walk through" path. Nevertheless, I want to see TRANSACTIONS instead. I found that if I change
if (!isFocused && !event.defaultPrevented) {
const jumpToAction = TabActions.jumpTo(options.title || 'Home');
navigation.dispatch(jumpToAction);
}
to
if (!isFocused && !event.defaultPrevented) {
navigation.reset({ index, routes: [{ name: route.name }] });
}
it more or less does the thing. But it resets the navigation, so it is unmounted and on return back, all data are lost and need to refetch.
In navigation is PopToTop() function that is not available in this scope.
Also I tried to access all nested navigators through descriptors, yet I have not found how to correctly force them to popToTop.
And the idea is do it on one place so it will be handled automatically and there would not be any need to implement it on each screen.
I have tried with navigator.popToTop() but it was not working. It may be stackNavigator and TabNavigator having a different history with the routes. I have fixed the issue with the below code. "Home" is my stack navigator name and another "Home" is screen name (Both are same for me)
tabBarButton: props => (
<TouchableOpacity
{...props}
onPress={props => {
navigation.navigate('Home', {
screen: 'Home'
})
}}
/>
),

Nested MaterialUI Tabs throws an error when opening second tabs level

I am trying to build a nested horizontal tabs in MaterialUI, I mean, a first tabs level that, when you click on it, open a second tabs level.
Here is a link to the working replicable code example: https://codesandbox.io/s/sweet-pasteur-x4m8z?file=/src/App.js
The problem is: When I click on first level, second level is opened, when I click on a item from second level, I get this error
Material-UI: the value provided to the Tabs component is invalid.
None of the Tabs' children match with "value21".
You can provide one of the following values: value11
For replicate the error, you could do next steps:
Click in "Label 1"
Click in "Label 1.1"
Error is thrown
I do not understand why that error, if I am splitting values of each tab in different states and, supposedly, it is all Ok. Maybe the way I use for implementing the nested tab is wrong, any idea what could be happening?
Thank you.
I created three tab components, one parent and two children. Then I Imported the children tab components into the parent. You can use vertical tabs for the child tab components to help with the layout. check out the how the parent tab looks like. Note all these are tab components
// Parent tab component
import React from 'react';
import PropTypes from 'prop-types';
import SwipeableViews from 'react-swipeable-views';
import { makeStyles, useTheme } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import Typography from '#material-ui/core/Typography';
import Box from '#material-ui/core/Box';
function TabPanel(props) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`full-width-tabpanel-${index}`}
aria-labelledby={`full-width-tab-${index}`}
{...other}
>
{value === index && (
<Box p={3}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
};
function a11yProps(index) {
return {
id: `full-width-tab-${index}`,
'aria-controls': `full-width-tabpanel-${index}`,
};
}
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: theme.palette.background.paper,
width: 500,
},
}));
export default function FullWidthTabs() {
const classes = useStyles();
const theme = useTheme();
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const handleChangeIndex = (index) => {
setValue(index);
};
return (
<div className={classes.root}>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
aria-label="full width tabs example"
>
<Tab label="Item One" {...a11yProps(0)} />
<Tab label="Item Two" {...a11yProps(1)} />
</Tabs>
</AppBar>
<SwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={value}
onChangeIndex={handleChangeIndex}
>
<TabPanel value={value} index={0} dir={theme.direction}>
<ChildTabOne/>
</TabPanel>
<TabPanel value={value} index={1} dir={theme.direction}>
<ChildTabTwo/>
</TabPanel>
</SwipeableViews>
</div>
);
}

React Router with - Ant Design Sider: how to populate content section with components for relevant menu item

I'm trying to use AntD menu sider like a tab panel.
I want to put components inside the content so that the content panel renders the related component when a menu item is clicked.
How do I get this structure to take components as the content for each menu item?
import React from 'react';
import { compose } from 'recompose';
import { Divider, Layout, Card, Tabs, Typography, Menu, Breadcrumb, Icon } from 'antd';
import { PasswordForgetForm } from '../Auth/Password/Forgot';
const { Title } = Typography
const { TabPane } = Tabs;
const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;
class Dashboard extends React.Component {
state = {
collapsed: false,
};
onCollapse = collapsed => {
console.log(collapsed);
this.setState({ collapsed });
};
render() {
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}>
<div />
<Menu theme="light" defaultSelectedKeys={['1']} mode="inline" >
<Menu.Item key="1">
<Icon type="fire" />
<span>Next item</span>
<PasswordForgetForm />
</Menu.Item>
<Menu.Item key="2">
<Icon type="fire" />
<span>Next item</span>
<Another component to render in the content div />
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header style={{ background: '#fff', padding: 0 }} />
<Content style={{ margin: '0 16px', background: '#fff' }}>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
RENDER RELEVANT COMPONENT HERE BASED ON MENU ITEM SELECTED
</div>
</Content>
</Layout>
</Layout>
);
}
}
export default Dashboard;
When I try to render this, no errors are thrown, but the content div does not update with the PasswordForgetForm that I specified as the content for the menu item.
I tried Chris' suggestion below - which works fine to render the component for each of the different menu item content divs in the layout segment, however - the downside of this approach is that with every page refresh, the path goes to the content component for that particular menu item, instead of the test page which has the menu on it -- and the content component with that relevant content. If this approach is endorsed as sensible, is there a way to keep the page refresh on the original page, rather than trying to go to a subset menu item url?
Update
I found this literature. I think this might be what I need to know, but the language is too technical for me to understand. Can anyone help with a plain english version of this subject matter?
I also found this tutorial which uses Pose to help with rendering. While this structure is what I'm trying to achieve, it looks like Pose has been deprecated. Does anyone know if its necessary to go beyond react-router to get this outcome, or is there a solution within react that I can look to implement?
This example is similar to what I want, but I can't find anything that defines sidebar (which seems to be an argument that is necessary to make this work).
I have also seen this post. While some of the answers are a copy and paste of the docs, I wonder if the answer by Adam Gering is closer to what I need. I'm trying to keep the Sider menu on the /dash route at all times. That url should not change - regardless of which menu item in the sider the user clicks BUT the content div in the /dash component should be updated to render the component at the route path I've specified.
APPLYING CHRIS' SUGGESTION
Chris has kindly offered a suggestion below. I tried it, but the circumstance in which it does not perform as desired is when the menu item is clicked (and the relevant component correctly loads in the content div, but if I refresh the page, the refresh tries to load a page with a url that is for the component that is supposed to be inside the content div on the dashboard page.
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
} from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import { compose } from 'recompose';
import { Divider, Layout, Card, Tabs, Typography, Menu, Breadcrumb, Icon } from 'antd';
import { withFirebase } from '../Firebase/Index';
import { AuthUserContext, withAuthorization, withEmailVerification } from '../Session/Index';
// import UserName from '../Users/UserName';
import Account from '../Account/Index';
import Test from '../Test/Index';
const { Title } = Typography
const { TabPane } = Tabs;
const { Header, Content, Footer, Sider } = Layout;
const { SubMenu } = Menu;
class Dashboard extends React.Component {
state = {
collapsed: false,
};
onCollapse = collapsed => {
console.log(collapsed);
this.setState({ collapsed });
};
render() {
const { loading } = this.state;
// const dbUser = this.props.firebase.app.snapshot.data();
// const user = Firebase.auth().currentUser;
return (
<AuthUserContext.Consumer>
{authUser => (
<div>
{authUser.email}
<Router>
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={this.state.collapsed} onCollapse={this.onCollapse}>
<div />
<Menu theme="light" defaultSelectedKeys={['1']} mode="inline" >
<SubMenu
key="sub1"
title={
<span>
<Icon type="user" />
<span>Profile</span>
</span>
}
>
<Menu.Item key="2"><Link to={ROUTES.ACCOUNT}>Account Settings</Link></Menu.Item>
<Menu.Item key="3"><Link to={ROUTES.TEST}>2nd content component</Link></Menu.Item>
</SubMenu>
</Menu>
</Sider>
<Layout>
<Header> </Header>
<Content style={{ margin: '0 16px', background: '#fff' }}>
<div style={{ padding: 24, background: '#fff', minHeight: 360 }}>
<Switch>
<Route path={ROUTES.ACCOUNT}>
<Account />
</Route>
<Route path={ROUTES.TEST}>
< Test />
</Route>
</Switch>
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>
test footer
</Footer>
</Layout>
</Layout>
</Router>
</div>
)}
</AuthUserContext.Consumer>
);
}
}
export default Dashboard;
In my routes file, I have:
export const ACCOUNT = '/account';
I've also found this tutorial - which uses the same approach outlined above - and doesn't get redirected in the same way that my code does on page refresh. The tutorial uses Route instead of BrowserRouter - but otherwise I can't see any differences.
NEXT ATTEMPT
I saw this post (thanks Matt). I have tried to follow the suggestions in that post.
I removed the outer Router wrapper from the Dashboard page (there is a Router around App.js, which is where the route to Dashboard is setup).
Then, in my Dashboard, I changed the Content div to:
I added:
let match = useRouteMatch();
to the render method inside my Dashboard component (as shown here).
I added useRouteMatch to my import statement from react-router-dom.
This produces an error that says:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
There is more message in the error above but stack overflow won't allow me to post it because it has a short link
I don't know what I've done wrong in these steps, but if I comment out the let statement, the page loads.
When I go to /Dashboard and click "account", Im expecting the account component to render inside the content div I have in the layout on the Dashboard page. Instead, it redirects directly to a page at localhost3000/account (for which there is not page reference - it's just a component to render inside the Dashboard page).
So this is worse than the problem I started with - because at least at the start, the redirect only happened on page refresh. Now it happens immediately.
I found this repo that has examples of each kind of route. I can't see what it is doing that I am not.
This post seems to have had the same problem as me, and resolved it using the same approach as I have tried. It's a post from 2018 so may the passage of time makes the approach outdated - but I can't see any difference between what that post solution implements and my original attempt.
NEXT ATTEMPT
I had thought I had found an approach that works in Lyubomir's answer on this post.
I have:
<Menu.Item key="2">
<Link to=
{${this.props.match.url}/account}>
Account Settings
Then in the div on the dash component where I want to display this component I have:
<div>
<Switch>
<Route exact path={`${this.props.match.url}/:account`} component={Account} />
This works. On page refresh, I can keep things working as they should.
HOWEVER, when I add a second menu item with:
<Menu.Item key="16">
<Link to={`${this.props.match.url}/learn`}>
<Icon type="solution" />
<span>Lern</span>
</Link>
</Menu.Item>
Instead of rendering the Learning component when menu item for /learn is clicked (and the url bar changes to learn), the Account component is rendered. If i delete the account display from the switch statement, then I can have the correct Learning component displayed.
With this attempt, I have the menu items working to match a Dashboard url extension (ie localhost/dash/account or localhost/dash/learn) for ONE menu item only. If I add a second menu item, the only way I can correctly render the 2nd component, is by deleting the first menu item. I am using switch with exact paths.
I want this solution to work with multiple menu items.
I have tried alternating path for url (eg:
<Link to={`${this.props.match.url}/learn`}>
is the same as:
<Link to={`${this.props.match.path}/learn`}>
I have read the explanation in this blog and while I don't entirely understand these options. I have read this. It suggests the match statement is now a legacy method for rendering components (now that hooks are available). I can't find any training materials that show how to use hooks to achieve the expected outcome.
The better solution is using React Router <Link> to make each menu item link to a specific path, and then in the content, using <Switch> to render the corresponding component. Here's the doc: React router
Render With React Router
<Router>
<Layout style={{ minHeight: "100vh" }}>
<Sider
collapsible
collapsed={this.state.collapsed}
onCollapse={this.onCollapse}
>
<div />
<Menu theme="light" defaultSelectedKeys={["1"]} mode="inline">
<Menu.Item key="1">
// Add a react router link here
<Link to="/password-forget-form">
<Icon type="fire" />
<span>Next item</span>
</Link>
</Menu.Item>
<Menu.Item key="2">
// Add another react router link
<Link to="/next-item">
<Icon type="fire" />
<span>Next item</span>
</Link>
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header style={{ background: "#fff", padding: 0 }} />
<Content style={{ margin: "0 16px", background: "#fff" }}>
<div style={{ padding: 24, background: "#fff", minHeight: 360 }}>
// Render different components based on the path
<Switch>
<Route path="/password-forget-form">
<PasswordForgetForm />
</Route>
<Route path="/next-item">
<Another component to render in the content div />
</Route>
</Switch>
</div>
</Content>
</Layout>
</Layout>
</Router>;
Render With Menu Keys
App.js
import React, { useState } from "react";
import { Layout } from "antd";
import Sider from "./Sider";
import "./styles.css";
const { Content } = Layout;
export default function App() {
const style = {
fontSize: "30px",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center"
};
const components = {
1: <div style={style}>Option 1</div>,
2: <div style={style}>Option 2</div>,
3: <div style={style}>Option 3</div>,
4: <div style={style}>Option 4</div>
};
const [render, updateRender] = useState(1);
const handleMenuClick = menu => {
updateRender(menu.key);
};
return (
<div className="App">
<Layout style={{ minHeight: "100vh" }}>
<Sider handleClick={handleMenuClick} />
<Layout>
<Content>{components[render]}</Content>
</Layout>
</Layout>
</div>
);
}
Sider.js
import React from "react";
import { Menu, Layout, Icon } from "antd";
const { SubMenu } = Menu;
export default function Sider(props) {
const { handleClick } = props;
return (
<Layout.Sider>
<Menu theme="dark" mode="inline" openKeys={"sub1"}>
<SubMenu
key="sub1"
title={
<span>
<Icon type="mail" />
<span>Navigation One</span>
</span>
}
>
<Menu.Item key="1" onClick={handleClick}>
Option 1
</Menu.Item>
<Menu.Item key="2" onClick={handleClick}>
Option 2
</Menu.Item>
<Menu.Item key="3" onClick={handleClick}>
Option 3
</Menu.Item>
<Menu.Item key="4" onClick={handleClick}>
Option 4
</Menu.Item>
</SubMenu>
</Menu>
</Layout.Sider>
);
}
I found Lyubomir's answer on this post. It works. Nested routes with react router v4 / v5
The menu item link is:
<Menu.Item key="2">
<Link to=
{`${this.props.match.url}/account`}>
Account
</Link>
</Menu.Item>
The display path is:
<Route exact path={`${this.props.match.path}/:account`} component={Account} />
There is a colon before the name of the component. Not sure why. If anyone knows what this approach is called - I'd be grateful for a reference so that i can try to understand it.
I am using antd >=4.20.0, as a side effect Menu.Item is deprecated. While above solution works, It does warn about discontinuing support. So thats not a long term solution.
Check here for details on 4.20.0 changes.
Long term solution is that instead of Menu.Item we need to use items={[]}. But with that <Link> doesn't work as API doesn't have support and we cant pass it as child component.
I looked around, after much search and combining information from various sources, what worked was,
use useNavigate() to change pages using onClick in Menu items[].
use useLocation().pathname to get path and pass it up as selectedKey
Define routes in <Content>.
Here's working example [ stripped to skeleton code to illustrate concept]
#index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
#App.js
import React, {useState} from 'react';
import { Layout, Menu, Tooltip } from 'antd'
import {
MenuUnfoldOutlined,
MenuFoldOutlined,
TeamOutlined,
UserOutlined,
} from '#ant-design/icons'
import { useLocation, useNavigate, Route, Routes } from 'react-router-dom'
import './App.less';
import 'antd/dist/antd.min.css';
const { Content, Sider } = Layout;
const Page1 = () => {
return <h4> Page 1</h4>
}
const Page2 = () => {
return <h4> Page 2</h4>
}
const App = () => {
const [collapsed, setCollapsed] = useState(true);
const toggleCollapsed = () => {
setCollapsed(!collapsed);
};
let navigate = useNavigate();
const selectedKey = useLocation().pathname
const highlight = () => {
if (selectedKey === '/'){
return ['1']
} else if (selectedKey === '/page2'){
return ['2']
}
}
return (
<Layout className="site-layout">
<Sider trigger={null} collapsible collapsed={collapsed}>
<div className="logo">
<Tooltip placement="right" arrowPointAtCenter title="Expand / Shrink Menu" >
{React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
className: 'trigger',
onClick: toggleCollapsed,
})}
</Tooltip>
</div>
<Menu
mode="inline"
theme="light"
defaultSelectedKeys={['1']}
selectedKeys={highlight()}
style={{ height: '100%', borderRight:0 }}
items={[
{
key: '1',
icon: <UserOutlined />,
label: "Page 1",
onClick: () => { navigate('/')}
},
{
key: '2',
icon: <TeamOutlined />,
label: "Page 2",
onClick: () => { navigate('/page2')}
}
]}
/>
</Sider>
<Content>
<Routes>
<Route exact path="/" element={<Page1 />} />
<Route path="/page2" element={<Page2 />} />
</Routes>
</Content>
</Layout>
)
}
export default App;
#Resulting Page
Just an update to wei-su's answer above:
antd has declared the deprecation of using Menu.item components after version 4.20.0. A quick and dirty hack could be nesting the react router <Link> inside label of the antdesign menu:
import { Icon, Menu } from "antd";
import { Link } from "react-router-dom";
// and the other imports ...
const items = [
{
path: "/some-path",
label: "a menu item",
icon: <Icon type="fire" />,
},
{
path: "/another-path",
label: "another menu item",
icon: <Icon type="fire" />,
},
].map((item, index) => {
return {
key: index,
label: <Link to={item.path}>{item.label}</Link>,
icon: item.icon,
};
});
and then when rendering Menu:
<Menu
mode="inline"
items={items}
defaultSelectedKeys={["0"]}
/>

Passing a component a navigation screen via props from screen component

I am building an app that has a list on the home screen routing to a number of other screens.
I created a list component that is rendered on the home page, and therefore, need to pass the navigation down to the list component. The list component, in turn, will determine which screen to display depending on which item is pressed.
I am using a Stack Navigator on my router.js file
export const HomeStack = StackNavigator({
Home: {
screen: Home,
navigationOptions: {
title: 'Home',
},
},
Nutrition: {
screen: Nutrition,
navigationOptions: {
title: 'Nutrition',
}
},
});
In my home.js screen I have the below code inside the render method
render() {
return (
<View>
<View>
<ListComponent navigate={this.props.navigation.navigate('')} />
<Button
title="Go to Nutrition"
onPress={() => this.props.navigation.navigate('Nutrition')}
/>
</View>
</View>
);
}
The Button successfully routes to the Nutrition.js screen.
But, I try to get my ListComponent.js to handle where to route as this file maps through my list array.
render() {
return (
<List>
{ListData.map((listItem, i) => (
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={this.onPressHandler(listItem.title)}
/>
))}
</List>
);
}
How can I properly pass the navigation as props down to ListComponent.js and then use the title from the list array to determine which screen to display?
change this line :
<ListComponent navigate={this.props.navigation.navigate('')} />
to this :
<ListComponent navigate={(screen)=>this.props.navigation.navigate(screen)}/>
and change this
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={this.onPressHandler(listItem.title)}
/>
to this :-
<ListItem
key={i}
title={listItem.title}
leftIcon={{ name: listItem.icon }}
onPress={()=>this.props.navigate(listItem.title)}
/>
As you are calling the method directly not binding it to the component.
I am assuming that your code in ListItem.js is correct.

Categories

Resources