Hey Guys I have an irritating problem with my code. I am rendering the user name and logout button in the navbar based on whether the user is not null and if it is null then I am rendering sign-in and sign-up links. But the problem arises it keeps saying that Cannot read properties of null (reading 'user') so if it is null it should render the navbar with sign-in and sign-up but it is giving an error can anybody solve my problem.
App.js
import { Switch, Route } from "react-router-dom";
import Home from "./pages/Home";
import SignInSide from "./pages/SignIn";
import SignUpSide from "./pages/SignUp";
import SignUpUser from "./pages/SignUpUser";
import AddAdmin from "./pages/AddAdmin";
import Dashboard from "./pages/Dashboard";
import AppAppBar from "./components/AppAppBar";
import withRoot from "./withRoot";
import { UsersContextProvider } from "./global/UsersContext";
import { SellersContextProvider } from "./global/SellersContext";
import { VerifySellersContextProvider } from "./global/VerifySellersContext";
import { RejectSellersContextProvider } from "./global/RejectSellersContext";
import { useEffect, useState } from "react";
import { auth, db } from "../src/config/Config";
function App() {
//create a state to store user data
const [userData, setuserData] = useState(null);
useEffect(() => {
//check if any change in auth state change
auth.onAuthStateChanged((user) => {
if (user !== null) {
console.log(user);
db.collection("SignedUpUsersData")
.doc(user.uid)
.get()
.then((snapshot) => {
//set teh userData STATE
setuserData({
user: snapshot.data().Name,
});
});
} else {
setuserData({
user: null,
});
}
});
}, []);
return (
<div>
<RejectSellersContextProvider>
<VerifySellersContextProvider>
<SellersContextProvider>
<UsersContextProvider>
{/* This is where the user object have been passed and it is navbar */}
<AppAppBar user={userData} />
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
<Route path="/signin">
<SignInSide />
</Route>
<Route path="/signup">
<SignUpSide />
</Route>
<Route path="/signupuser">
<SignUpUser />
</Route>
<Route path="/addadmin">
<AddAdmin />
</Route>
</Switch>
</UsersContextProvider>
</SellersContextProvider>
</VerifySellersContextProvider>
</RejectSellersContextProvider>
</div>
);
}
export default withRoot(App);
AppAppBar.js
import * as React from "react";
import Box from "#mui/material/Box";
import Link from "#mui/material/Link";
import AppBar from "../subcomponents/AppBar";
import Toolbar from "../subcomponents/Toolbar";
import Button from "#mui/material/Button";
import Stack from "#mui/material/Stack";
import { Link as RouterLink } from "react-router-dom";
import { auth } from "../config/Config";
import { useHistory } from "react-router-dom";
const rightLink = {
fontSize: 16,
color: "common.white",
ml: 3,
};
const button = {
fontSize: 16,
color: "red",
ml: 3,
cursor: "pointer",
};
function AppAppBar({ user }) {
const history = useHistory();
const logut = () => {
auth.signOut().then(() => {
history.push("/signin");
console.log("user has singned out");
});
};
console.log(user);
return (
<div>
<AppBar position="fixed">
<Toolbar
sx={{ justifyContent: "space-between", backgroundColor: "black" }}
>
<Box sx={{ flex: 1, display: "flex", justifyContent: "flex-start" }}>
<Link
component={RouterLink}
to="/"
variant="h6"
underline="none"
color="inherit"
sx={{ fontSize: 24, color: "white" }}
>
{"tenderdash"}
</Link>
</Box>
<Box sx={{ flex: 1, display: "flex", justifyContent: "flex-end" }}>
<Link
color="inherit"
variant="h6"
underline="none"
href="/premium-themes/onepirate/sign-in/"
sx={rightLink}
>
{"Products"}
</Link>
<Link
color="inherit"
variant="h6"
underline="none"
href="/premium-themes/onepirate/sign-in/"
sx={rightLink}
>
{"List Equipments"}
</Link>
<Link
color="inherit"
variant="h6"
underline="none"
href="/premium-themes/onepirate/sign-in/"
sx={rightLink}
>
{"Contact Us"}
</Link>
{/* if there is not a user */}
{user.user === null && (
<div>
<Link
component={RouterLink}
to="/signin"
color="inherit"
variant="h6"
underline="none"
sx={rightLink}
>
{"SignIn"}
</Link>
<Link
component={RouterLink}
to="/signup"
variant="h6"
underline="none"
sx={rightLink}
>
{"Sign Up"}
</Link>
</div>
)}
{/* if there is a user */}
{user.user && (
<>
<Link variant="h6" underline="none" sx={rightLink}>
{user.user}
</Link>
<Link onClick={logut} sx={button} variant="h6">
Logout
</Link>
</>
)}
{/* if the user is admin */}
{/* <Link
component={RouterLink}
to="/dashboard"
variant="h6"
underline="none"
sx={{ ...rightLink, color: "secondary.main" }}
>
{"Admin Console"}
</Link> */}
</Box>
</Toolbar>
</AppBar>
<Toolbar />
</div>
);
}
export default AppAppBar;
When you initialize userData , you are initializing with null, then in your component AppAppBar in the line user.user is the same than null.user, this is the error.
You should replace this:
const [userData, setuserData] = useState(null)
by:
const [userData, setuserData] = useState({user: null})
Related
Here is my *Navbar
import React, { useState } from "react";
import { Layout, Menu } from "antd";
import {
MenuUnfoldOutlined,
MenuFoldOutlined,
UserOutlined,
VideoCameraOutlined,
UploadOutlined,
} from "#ant-design/icons";
import { Link } from "react-router-dom";
const { Header, Sider, Content } = Layout;
const Navbar = (props) => {
const [collapsed, setCllapsed] = useState(false);
const toggle = () => {
setCllapsed(!collapsed);
};
return (
<div>
<Layout id="components-layout-demo-custom-trigger">
<Sider trigger={null} collapsible collapsed={collapsed}>
<div className="logo" />
<Menu theme="dark" mode="inline" defaultSelectedKeys={["1"]}>
<Menu.Item key="1" icon={<UserOutlined />}>
<Link style={{ textDecoration: "none" }} to="/">
Dashboard
</Link>
</Menu.Item>
<Menu.Item key="2" icon={<UserOutlined />}>
<Link style={{ textDecoration: "none" }} to="/groups">
Groups
</Link>
</Menu.Item>
<Menu.Item key="3" icon={<VideoCameraOutlined />}>
<Link style={{ textDecoration: "none" }} to="/tutors">
Tutors
</Link>
</Menu.Item>
<Menu.Item key="4" icon={<UserOutlined />}>
<Link style={{ textDecoration: "none" }} to="/students">
Students
</Link>
</Menu.Item>
</Menu>
</Sider>
<Layout className="site-layout">
<Header className="site-layout-background" style={{ padding: 0 }}>
{React.createElement(
collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
{
className: "trigger",
onClick: toggle,
}
)}
</Header>
<Content
className="site-layout-background"
style={{
margin: "24px 16px",
padding: 24,
minHeight: 280,
}}
>
{props.children}
</Content>
</Layout>
</Layout>
</div>
);
};
export default Navbar;
In this example I was using <Menu.Item></Menu.Item> component from antd . But it stopped working when clicked once. It changed onclick function. After adding from react-router-dom, I am having trouble with SelectedKeys of Antdesign's Layout. Before Link component of react-router-dom selectedKeys was working when you click one time, but after adding Link component, SelectedKeys is working when double clicked. How can I solve it? I need this should work once. Anyone can help me?
I am using react router dom v6 and want to implement a logic where the sidebar will be available across all the components in my. Currently whenever i try to click any in side bar the side bar is vanishing.
I want to keep the side bar across all the components in my app.
Side Bar available
Sidebar gone
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter as Router, Routes, Route,Navigate,Link} from
'react-router-dom'; import Login from
'../src/components/Login/LoginPage'; import Test from
'../src/components/test/Test'; import Homepage from
'../src/components/homepage/HomePage'; import Scheduler from
'../src/components/scheduler/Scheduler'; import Classroom from
'../src/components/classroom/Classroom'; import Assignment from
'../src/components/assignment/Assignment'; import Meeting from
'../src/components/meetings/Meetings'; import ReportCard from
'../src/components/reportcard/ReportCard'; import SideMenuBar from
'../src/components/sidemenubar/SideMenuBar'; ReactDOM.render(
<Router>
<Routes>
<Route path='/' element={<Login />} />
<Route path='/api/v1/testpath' element={<Test />} />
{/* Sidebar Routes */}
<Route path="/api/v1/app/userHome" exact element={<Test />} />
<Route path="/api/v1/app/schedule" exact element={<Scheduler />} />
<Route path="/api/v1/app/myclassroom" exact element={<Classroom />} />
<Route
path="/api/v1/app/myassignments"
exact
element={<Assignment />}
/>
<Route path="/api/v1/app/mymeetings" exact element={<Meeting />} />
<Route path="/api/v1/app/viewreports" exact element={<ReportCard />} />
</Routes>
</Router>,
document.getElementById('root')
);
Sidebar.js
import {
ListItemIcon,
ListItemText,
List,
Divider,
Drawer,
Avatar,
Box,
ListItemButton,
} from "#mui/material";
import { makeStyles } from "#mui/styles";
import HomeIcon from "#mui/icons-material/Home";
import WatchLaterIcon from "#mui/icons-material/WatchLater";
import GroupsIcon from "#mui/icons-material/Groups";
import AssignmentOutlinedIcon from "#mui/icons-material/AssignmentOutlined";
import AssessmentOutlinedIcon from "#mui/icons-material/AssessmentOutlined";
import LogoutOutlinedIcon from "#mui/icons-material/LogoutOutlined";
import MeetingRoomOutlinedIcon from "#mui/icons-material/MeetingRoomOutlined";
import Logo from "./logo.png";
import { BrowserRouter as Router, Route, Link, Routes } from "react-router-dom";
import Homepage from "../homepage/HomePage";
import Scheduler from "../scheduler/Scheduler";
import Classroom from "../classroom/Classroom";
import Assignment from "../assignment/Assignment";
import ReportCard from "../reportcard/ReportCard";
import Meeting from "../meetings/Meetings";
const drawerWidth = 350;
const useStyles = makeStyles({
page: {
background: "#f9f9f9",
width: "100%",
},
root: {
display: "flex",
},
drawer: {
width: drawerWidth,
},
drawerPaper: {
width: drawerWidth,
borderRadius: "2%",
},
listitem: {
"&:hover": {
fontWeight: "fontWeightBold",
background: "#f9f9f9",
},
},
navlink: {
textDecoration: "inherit",
color: "inherit",
},
});
export default function Sidemenubar() {
const classes = useStyles();
return (
<Box sx={{ display: "flex" }}>
<Divider />
<Drawer
className={classes.drawer}
variant="permanent"
classes={{ paper: classes.drawerPaper }}
anchor="left"
>
{/*App Logo */}
<Avatar
src={Logo}
alt="404"
sx={{ width: 100, height: 100, alignSelf: "center", margin: 1 }}
/>
{/*Menu Items */}
<List component="nav">
<Link to="/api/v1/app/userHome" className={classes.navlink}>
<ListItemButton
sx={{
"&:hover": {
fontWeight: "bold",
boxShadow: 1,
background: "#6D62DA",
},
}}
>
<ListItemIcon>
<HomeIcon />
</ListItemIcon>
<ListItemText primary="Home" />
</ListItemButton>
</Link>
<Divider />
<Link to="/api/v1/app/schedule" className={classes.navlink}>
<ListItemButton
sx={{
"&:hover": {
fontWeight: "bold",
boxShadow: 1,
background: "#6D62DA",
},
}}
>
<ListItemIcon>
<WatchLaterIcon />
</ListItemIcon>
<ListItemText primary="Scheduler" />
</ListItemButton>
</Link>
<Divider />
</List>
</Drawer>
<Routes>
<Route path='/api/v1/app/userHome' element={<Homepage />}></Route>
<Route path='/api/v1/app/schedule' element={<Scheduler />}></Route>
</Routes>
</Box>
);
}
HomePage.js
import React from 'react';
import { Grid } from "#mui/material";
import SideMenuBar from '../sidemenubar/SideMenuBar';
import HomePage from '../homepage/HomePage';
import Scheduler from '../scheduler/Scheduler';
import {BrowserRouter as Router,
Routes, Route,Navigate,Link} from 'react-router-dom';
class Test extends React.Component{
render(){
return (
<Grid container>
<Grid item md={4}>
<SideMenuBar />
</Grid>
<Grid item md={8}>
<HomePage />
</Grid>
</Grid>
)
}
}
export default Test;
If you want to render a sidebar on every route/page then I suggest:
Using Layout Wrapper Component and Outlet
Create a layout container component that renders the Sidebar component and an Outlet into the respective grid columns. Render the page routes nested into the layout.
import { Outlet } from 'react-router-dom';
import SideMenuBar from '../sidemenubar/SideMenuBar';
const PageLayout = () => (
<Grid container>
<Grid item md={4}>
<SideMenuBar />
</Grid>
<Grid item md={8}>
<Outlet /> // <-- nested routes rendered here
</Grid>
</Grid>
);
index.js
<Router>
<Routes>
<Route path="/" element={<PageLayout />} >
<Route index element={<Login />} />
<Route path="/api/v1/app/userHome" element={<UserHome />} />
<Route path="/api/v1/app/schedule" element={<Scheduler />} />
<Route path="/api/v1/app/myclassroom" element={<Classroom />} />
<Route
path="/api/v1/app/myassignments"
element={<Assignment />}
/>
<Route path="/api/v1/app/mymeetings" element={<Meeting />} />
<Route path="/api/v1/app/viewreports" element={<ReportCard />} />
</Route>
</Routes>
</Router>
Using Wrapper Component and children Prop
An alternative would be to have the PageLayout component render its children instead, and wrap the Routes component.
const PageLayout = ({ children }) => (
<Grid container>
<Grid item md={4}>
<SideMenuBar />
</Grid>
<Grid item md={8}>
{children}
</Grid>
</Grid>
);
index.js
<Router>
<PageLayout>
<Routes>
<Route path="/ element={<Login />} />
<Route path="/api/v1/app/userHome" element={<UserHome />} />
<Route path="/api/v1/app/schedule" element={<Scheduler />} />
<Route path="/api/v1/app/myclassroom" element={<Classroom />} />
<Route
path="/api/v1/app/myassignments"
element={<Assignment />}
/>
<Route path="/api/v1/app/mymeetings" element={<Meeting />} />
<Route path="/api/v1/app/viewreports" element={<ReportCard />} />
</Routes>
</PageLayout>
</Router>
I am trying to create a page that contains a list of cards. I designed the Header of the page but as a beginner, but I created it in my own way.
Problem is that when I am trying to display the card in the new Grid container its will not showing the desired result.
Here the Image with the head I created
Here the I the problem picture when I try to put Grid container
My Style and Code :
import { AppBar, Avatar, Button, Card, CardActionArea, CardActions, CardContent, CardMedia, Grid, IconButton, makeStyles, Toolbar, Typography } from '#material-ui/core';
import React from 'react';
import MenuIcon from '#material-ui/icons/Menu';
import { Link } from 'react-router-dom';
const useStyles = makeStyles((theme) => ({
blackBox: {
backgroundColor: 'black',
height: '350px'
},
AppBar: {
'&.MuiAppBar-positionFixed': {
top: '60px',
right: '126px',
'#media (max-width: 576px)': {
right: '42px'
}
},
width: '85%',
},
large: {
width: theme.spacing(10),
height: theme.spacing(10),
},
link: {
color: 'white',
textDecoration: 'none',
marginLeft: '30px',
fontFamily: 'Times new roman'
},
headText: {
marginTop: '130px',
'#media (max-width: 576px)': {
marginTop: '170px',
}
},
title: {
color: 'white',
'#media (max-width: 576px)': {
fontSize: '30px'
}
},
titleDesc: {
color: 'white',
'#media (max-width: 576px)': {
width: '235px'
}
}
}))
export default function CoursesView() {
const classes = useStyles();
return (
<>
<Grid container
direction="column"
// justify="space-evenly"
alignItems="center"
className={classes.blackBox}
>
<Grid item >
<AppBar className={classes.AppBar} color='transparent'>
<Toolbar>
{/* <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
<MenuIcon />
</IconButton> */}
<div style={{ flexGrow: '1' }}>
<Avatar alt="Remy Sharp" src="https://seeklogo.com/images/F/forex-logo-6B4D0AB43E-seeklogo.com.png" className={classes.large} />
</div>
<Link to='/play' className={classes.link}>Home</Link>
<Link to='/play' className={classes.link}>Courses</Link>
<Link to='/play' className={classes.link}>The Trade Signal</Link>
<Link to='/play' className={classes.link}>About</Link>
<Link to='/play' className={classes.link}>My Account</Link>
<Link to='/play' className={classes.link}>My Crat</Link>
</Toolbar>
</AppBar>
</Grid>
<Grid item container className={classes.headText} direction="column"
justify="center"
alignItems="center">
<Typography variant="h2" className={classes.title}>
Courses
</Typography>
<Typography variant="p" className={classes.titleDesc}>
our uniqly designed courses will help you in your specific areas of needs
</Typography>
</Grid>
</Grid>
<Grid container>
<h1>The cards wil display Here</h1>
</Grid>
</>
)
}
enter code here
The main app file that renders this app
import React from "react";
import CourseListView from "./components/pages/CourseListView";
import VideoPlayView from "./components/pages/VideoPlayView";
import { Route, Switch } from "react-router-dom";
import { makeStyles, ThemeProvider } from "#material-ui/core/styles";
import { createMuiTheme } from '#material-ui/core';
import CoursesView from "./components/pages/CoursesView";
const useStyles = makeStyles({
container: {
display: "flex"
}
});
const theme = createMuiTheme({
palette: {
primary: {
main: "#333996",
light: "#3c44b126"
},
secondary: {
main: "#f83245",
light: "#f8324526"
},
background: {
default: "#f4f5fd"
},
},
overrides: {
MuiAppBar: {
root: {
transform: 'translateZ(0)',
}
}
}
})
export default function App() {
const classes = useStyles();
return (
<ThemeProvider theme={theme}>
<div className={classes.container}>
<Switch>
<Route exact from="/" render={props => <CourseListView {...props} />} />
<Route exact from="/play" render={props => <VideoPlayView {...props} />} />
<Route exact from="/Home" render={props => <CoursesView {...props} />} />
</Switch>
</div>
</ThemeProvider>
);
}
try this :
container: {
display: "flex",
flexDirection: column
}
I have React Router v5 with below code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
const muiTheme = createMuiTheme({
palette: {
primary: {
main: '#2196f3'
}
},
overrides: {
MUIDataTableSelectCell: {
fixedHeaderCommon: {
backgroundColor: 'transparent',
},
},
MuiTableCell: {
sizeSmall: {
padding: '6px 0 6px 16px'
}
},
MuiTableRow: {
hover: {
cursor: 'pointer'
}
}
}
});
ReactDOM.render(<MuiThemeProvider theme={muiTheme}><App /></MuiThemeProvider>, document.getElementById('root'));
serviceWorker.unregister();
App.js
import {
// BrowserRouter as Router,
Switch,
Route,
Router,
// Link,
// useRouteMatch,
// useParams
} from "react-router-dom";
import history from 'history/browser';
import Dashboard from './common/components/Dashboard';
import Login from './common/components/Login';
import Test from './common/components/Test';
<Router history={history}>
<Switch>
<Route path="/test" component={Test} />
<Route path="/login" component={Login} />
<Route path="/" exact component={Dashboard} />
<Route component={Error404} />
</Switch>
</Router>
Login.js
import { useHistory } from "react-router-dom";
export default function Login() {
let history = useHistory();
const classes = useStyles();
const storedToken = localStorage.getItem('token');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [remember, setRemember] = useState(false);
const [fetchError, setFetchError] = useState(null);
async function login(e) {
e.preventDefault();
try {
const data = await ApiClient.post(`/api/auth`, { email: email, password: password, remember: remember });
localStorage.setItem('token', data.token);
setFetchError(null);
history.push('/test');
} catch (err) {
if(err.response.status === 401) {
setFetchError('Unauthorized access, please login again.');
}
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Login
</Typography>
<form className={classes.form} noValidate onSubmit={login}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
onChange={(e) => setRemember(e.target.value)}
value={remember}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
}
Whenever I submit with correct credentials I get 200 response code from the server with JWT token but after history.push('/test'); on login function, I don't get the Route match with /test instead it goes to Error404 catch all route.
How is this possible?
It seems like a bug in history version 5. See this comment. When I downgraded to 4.10.1 it immediately worked
I'm completely new in MaterialUI. I'm working on my first project right now and trying to make use of templates form its page. I've loaded two .tsx files with log in view and main dashboard view. I'd like to show main dashboard view after clicking Login button on log in view. Both files have its own export default function FnName() function with const classes = useStyles(); and it seems to cause my problems. The way of using hooks is the issue here I guess. But how to pass this function to onClick handler event button? You can see my project here:
https://codesandbox.io/s/adoring-leftpad-6nwv2?file=/src/SignIn.tsx
Somebody can help?
Please check this example:
App Component
import React, {useEffect, useState} from 'react';
import SignIn from "./material-ui/signin-template/SignIn";
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";
import { createBrowserHistory as history} from 'history';
import MiniDrawer from "./material-ui/signin-template/Dashboard";
class App extends React.Component {
render() {
return (
<div>
<Router history={history}>
<Switch>
<Route path="/" exact component={SignIn}/>
<Route path="/dashboard" component={MiniDrawer}/>
</Switch>
</Router>
</div>
)
}
}
export default App;
SingIn Component
import React from "react";
import Avatar from "#material-ui/core/Avatar";
import Button from "#material-ui/core/Button";
import CssBaseline from "#material-ui/core/CssBaseline";
import TextField from "#material-ui/core/TextField";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import Link from "#material-ui/core/Link";
import Grid from "#material-ui/core/Grid";
import Box from "#material-ui/core/Box";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import Typography from "#material-ui/core/Typography";
import {makeStyles} from "#material-ui/core/styles";
import Container from "#material-ui/core/Container";
import {Redirect, useHistory} from "react-router-dom";
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{"Copyright © "}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const useStyles = makeStyles(theme => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center"
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: theme.spacing(1)
},
submit: {
margin: theme.spacing(3, 0, 2)
}
}));
export default function SignIn() {
const classes = useStyles();
let history = useHistory();
return (
<Container component="main" maxWidth="xs">
<CssBaseline/>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary"/>}
label="Remember me"
/>
<Button
onClick={()=>{
history.push('/dashboard')
}}
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link href="#" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright/>
</Box>
</Container>
);
}
Dashboard Component
import React from "react";
import clsx from "clsx";
import {
createStyles,
makeStyles,
useTheme,
Theme
} from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Drawer from "#material-ui/core/Drawer";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import List from "#material-ui/core/List";
import CssBaseline from "#material-ui/core/CssBaseline";
import Typography from "#material-ui/core/Typography";
import Divider from "#material-ui/core/Divider";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import ChevronLeftIcon from "#material-ui/icons/ChevronLeft";
import ChevronRightIcon from "#material-ui/icons/ChevronRight";
import ListItem from "#material-ui/core/ListItem";
import ListItemIcon from "#material-ui/core/ListItemIcon";
import ListItemText from "#material-ui/core/ListItemText";
import InboxIcon from "#material-ui/icons/MoveToInbox";
import MailIcon from "#material-ui/icons/Mail";
import MapOutlinedIcon from "#material-ui/icons/MapOutlined";
import DriveEtaOutlinedIcon from "#material-ui/icons/DriveEtaOutlined";
import PeopleAltOutlinedIcon from "#material-ui/icons/PeopleAltOutlined";
import DirectionsOutlinedIcon from "#material-ui/icons/DirectionsOutlined";
import AssessmentOutlinedIcon from "#material-ui/icons/AssessmentOutlined";
import ReportProblemOutlinedIcon from "#material-ui/icons/ReportProblemOutlined";
import AccountCircleOutlinedIcon from "#material-ui/icons/AccountCircleOutlined";
import { Redirect, useHistory } from "react-router-dom";
import ExitToAppIcon from "#material-ui/icons/ExitToApp";
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: "flex"
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
})
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(["width", "margin"], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
menuButton: {
marginRight: 36
},
hide: {
display: "none"
},
drawer: {
width: drawerWidth,
flexShrink: 0,
whiteSpace: "nowrap"
},
drawerOpen: {
width: drawerWidth,
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen
})
},
drawerClose: {
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
overflowX: "hidden",
width: theme.spacing(7) + 1,
[theme.breakpoints.up("sm")]: {
width: theme.spacing(9) + 1
}
},
toolbar: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar
},
content: {
flexGrow: 1,
padding: theme.spacing(3)
}
})
);
function MiniDrawer() {
const classes = useStyles();
let history = useHistory();
const theme = useTheme();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={clsx(classes.appBar, {
[classes.appBarShift]: open
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, {
[classes.hide]: open
})}
>
<MenuIcon />
</IconButton>
</Toolbar>
</AppBar>
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open
})
}}
>
<div className={classes.toolbar}>
<IconButton onClick={handleDrawerClose}>
{theme.direction === "rtl" ? (
<ChevronRightIcon />
) : (
<ChevronLeftIcon />
)}
</IconButton>
</div>
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<div className={classes.toolbar} />
<IconButton
onClick={() => {
history.push("/");
}}
>
<ExitToAppIcon />
</IconButton>
<Divider />
<List>
{["Mapa", "Pojazdy", "Kierowcy", "Trasy", "Raporty", "Alerty"].map(
(text, index) => (
<ListItem
button
key={text}
onClick={event => {
console.log(event.currentTarget);
history.push("/");
}}
>
<ListItemIcon>
{index === 0 && <MapOutlinedIcon />}
{index === 1 && <DriveEtaOutlinedIcon />}
{index === 2 && <PeopleAltOutlinedIcon />}
{index === 3 && <DirectionsOutlinedIcon />}
{index === 4 && <AssessmentOutlinedIcon />}
{index === 5 && <ReportProblemOutlinedIcon />}
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
)
)}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph />
</main>
</div>
);
}
export default MiniDrawer;
Here is the Code Sandbox