I am trying to use fullCalendar on my react project and I followed the steps that I saw on their docs, all plugins library that I am using, I install and imported but when I try to use eventsSet and change the State function I got a console error.
If I comment the eventsSet the Calendar works, does someone know what could be causing this?
my code:
https://github.com/wandersonce/Admin-Dashboard/blob/main/src/scenes/calendar/index.jsx
<pre>
import { useState } from 'react';
import FullCalendar from '#fullcalendar/react';
import { formatDate } from '#fullcalendar/core';
import dayGridPlugin from '#fullcalendar/daygrid';
import timeGridPlugin from '#fullcalendar/timegrid';
import interactionPlugin from '#fullcalendar/interaction';
import listPlugin from '#fullcalendar/list';
import {
Box,
List,
ListItem,
ListItemText,
Typography,
useTheme,
} from '#mui/material';
import Header from '../../components/Header';
import { tokens } from '../../theme';
export default function Calendar() {
const theme = useTheme();
const colors = tokens(theme.palette.mode);
const [currentEvents, setCurrentEvents] = useState([]);
const handleDateClick = (selected) => {
const title = prompt('Please enter a new title for your event');
const calendarApi = selected.view.calendar;
calendarApi.unselect();
if (title) {
calendarApi.addEvent({
id: `${selected.dateStr}-${title}`,
title,
start: selected.startStr,
end: selected.endStr,
allDay: selected.allDay,
});
}
};
const handleEventClick = (selected) => {
if (
window.confirm(
`Are you sure you want to delete the event '${selected.event.title}'`
)
) {
selected.event.remove();
}
};
return (
<Box m="20px">
<Header title="Calendar" subtitle="Full Calendar Interactive Page" />
<Box display="flex" justifyContent="space-between">
{/* CALENDAR SIDEBAR */}
<Box
flex="1 1 20%"
backgroundColor={colors.primary[400]}
p="15px"
borderRadius="4px"
>
<Typography variant="h5">Events</Typography>
<List>
{currentEvents.map((event) => (
<ListItem
key={event.id}
sx={{
backgroundColor: colors.greenAccent[500],
margin: '10px 0',
borderRadius: '2px',
}}
>
<ListItemText
primary={event.title}
secondary={
<Typography>
{formatDate(event.start, {
year: 'numeric',
month: 'short',
day: 'numeric',
})}
</Typography>
}
/>
</ListItem>
))}
</List>
</Box>
{/* CALENDAR */}
<Box flex="1 1 100%" ml="15px">
<FullCalendar
height="75vh"
plugins={[
dayGridPlugin,
timeGridPlugin,
interactionPlugin,
listPlugin,
]}
headerToolbar={{
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth',
}}
initialView="dayGridMonth"
editable={true}
selectable={true}
selectMirror={true}
dayMaxEvents={true}
select={handleDateClick}
eventClick={handleEventClick}
initialEvents={[
{
id: '12315',
title: 'All-day event',
date: '2022-09-14',
},
{
id: '5123',
title: 'Timed event',
date: '2022-09-28',
},
]}
eventsSet={(events) => setCurrentEvents(events)}
/>
</Box>
</Box>
</Box>
);
</pre>
and the error:
Related
I am complete my project. Now I am trying to get a production build. But I am getting an error with name "Component definition is missing display name". I am using nextjs.
From my whole proect only two component, show that error like image-
Clikc to see the image. I use material-table-core with mui5 in both component.
I am fully confused why I am seeing this error?
One of that component is-
import React from "react";
import { forwardRef } from "react";
import { Box, Stack, SvgIcon, Typography, ButtonBase, InputBase, Rating } from "#mui/material";
import { Star, ArrowDownward } from '#mui/icons-material';
import MaterialTable, { Column } from "#material-table/core";
//Custom Icon
import { DeleteIcon, ArrowUp, ArrowDown } from "Utilis/Icons";
//Theme
import theme from "Theme";
//Styles
import useStyles from "Styles/Common/DataTable.styles";
//Data
import cartData from "Data/Cart.data";
const DataTable = () => {
const classes = useStyles();
const columns = [
{ title: 'Product', field: 'product', cellStyle: { width: "75%" } },
{ title: 'Price', field: 'price', cellStyle: { width: "5%" } },
{ title: 'Quantity', field: 'quantity', cellStyle: { width: "10%" } },
{ title: 'Subtotal', field: 'subtotal', cellStyle: { width: "5%" } },
{ title: 'Remove', field: 'action', cellStyle: { width: "5%" } }
];
const data = [];
cartData && cartData.forEach(cart => {
data.push({
product: <Stack direction="row" sx={{ alignItems: "center" }}>
<Box>
<Box component="img" className={classes.ProductImages} src={cart.product.images[0].url} alt="Product Image" />
</Box>
<Box>
<Typography className={classes.ProductTitle} variant="h6" component="h6">
{cart.product.name}
</Typography>
<Rating
name="half-rating-read"
defaultValue={5}
precision={4}
readOnly
className={classes.Star}
emptyIcon={<Star fontSize="inherit" />}
/>
</Box>
</Stack>,
price: <Typography className={classes.ProductPrice} variant="h6" component="h6">
${cart.product.price}
</Typography>,
quantity:
<Box sx={{ position: "relative" }} className="sdfjshfggb">
<InputBase
className={classes.InputField}
value={cart.count}
type="text"
/>
<Box className={classes.CounterButton}>
<ButtonBase>
<SvgIcon viewBox="0 0 23 13">
{ArrowUp}
</SvgIcon>
</ButtonBase>
<ButtonBase>
<SvgIcon viewBox="0 0 23 13">
{ArrowDown}
</SvgIcon>
</ButtonBase>
</Box>
</Box>,
subtotal:
<Typography variant="h6" component="h6" className={classes.ProductPriceTotal}>
${cart.product.price * cart.count}
</Typography>,
action:
<ButtonBase className={classes.RemoveButton} >
<SvgIcon viewBox="0 0 24 24">{DeleteIcon}</SvgIcon>
</ButtonBase >
})
})
return (
<Box className={classes.DataTable}>
<MaterialTable
columns={columns}
data={data}
options={{
search: false,
showTitle: false,
toolbar: false,
selection: true,
paging: false,
headerStyle: {
backgroundColor: theme.palette.primary.input_bg,
color: theme.palette.primary.main,
}
}}
localization={{
body: {
emptyDataSourceMessage: (
<Typography variant="body1" component="p">
Cart is Empty!
</Typography>
),
},
}}
icons={{ SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />) }}
onSelectionChange={(e) => console.log(e)}
/>
</Box>
);
};
export default DataTable;
I am new in react/nextjs. This is my first project. Anyone can help me?
You are using an arrow funciton. You can either switch to a regular function, which will solve the problem of the displayName or you can set the displayName of the arrow function right before exporting it. Exporting an arrow function directly doesn't give the component a displayName.
DataTable.displayName = "DataTable"
export default DataTable;
import { ThemeProvider } from '#material-ui/core/styles'
import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import AppBar from '#material-ui/core/AppBar'
import Toolbar from '#material-ui/core/Toolbar'
import Tabs from '#material-ui/core/Tabs'
import Tab from '#material-ui/core/Tab'
import IconButton from '#material-ui/core/IconButton'
import MenuIcon from '#material-ui/icons/Menu'
import SwipeableDrawer from '#material-ui/core/SwipeableDrawer'
import { useMediaQuery, makeStyles } from '#material-ui/core'
import { useTheme } from '#material-ui/core/styles'
import { ListItem, ListItemText } from '#material-ui/core'
import logo from './logo.png'
const linksData = [
{
id: 1,
name: 'home',
path: '/',
},
{
id: 2,
name: 'portfolio',
path: '/portfolio',
},
{
id: 3,
name: 'services',
path: '/services',
},
{
id: 4,
name: 'about',
path: '/about',
},
]
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: '1',
},
contentItems: {
width: '100%',
height: '100%',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '0.5rem',
},
logo: {
width: '100%',
height: '4rem',
objectFit: 'cover',
},
logoContainer: {
flexBasis: '1',
display: 'flex',
alignItems: 'center',
},
linksContainer: {
flexBasis: '3',
},
link: {
textDecoration: 'none',
minWidth: 10,
},
}))
function App() {
const theme = useTheme()
const webView = useMediaQuery(theme.breakpoints.down('md'))
const classes = useStyles()
const [value, setValue] = useState(1)
const [openDrawer, setOpenDrawer] = useState(false)
const handleChange = (e, value) => setValue(value)
const iOS = process.browser && /iPad|iPhone|iPod/.test(navigator.userAgent)
return (
<>
<Router>
<ThemeProvider theme={theme}>
<Switch>
<Route path='/'>
<div className={classes.root}>
<AppBar>
<Toolbar>
<nav className={classes.contentItems}>
<div className={classes.logoContainer}>
<img src={logo} alt='logo' className={classes.logo} />
</div>
<Tabs value={value} onChange={handleChange}>
{linksData.map(({ path, name, id }) => {
console.log(path)
return (
<Tab
key={id}
value={id}
component={Link}
to={path.toString()}
className={classes.link}
label={name}
></Tab>
)
})}
</Tabs>
{webView && (
<IconButton onClick={() => setOpenDrawer(true)}>
<MenuIcon />
</IconButton>
)}
{openDrawer && (
<SwipeableDrawer
disableBackdropTransition={!iOS}
disableDiscovery={iOS}
open={openDrawer}
onOpen={() => setOpenDrawer(true)}
onClose={() => setOpenDrawer(false)}
>
<ListItem>
<ListItemText>hello</ListItemText>
<br />
<ListItemText>hello</ListItemText>
</ListItem>
</SwipeableDrawer>
)}
</nav>
</Toolbar>
</AppBar>
</div>
</Route>
</Switch>
</ThemeProvider>
</Router>
</>
)
}
export default App
I'm trying to implement a Swipeable Drawer, the drawer is visible, the fade out transition is smooth as well, however, the drawer does not translate smoothly, The drawer slides in and out without any transition style applied to it( which should be applied). One interesting case is that in case the "openDrawer" state is set to 'true', during initialization, the drawer translates smoothly, but beyond that, the transitions of the drawer are not smooth.
Here's a CodeSandBox link: https://codesandbox.io/s/xenodochial-ritchie-owen9
At first when I ran your sandbox and from what I can see it's running fine... I don't notice any jankiness when toggling the sidebar open/close.
BUT
As I was suspecting with the conditional rendering, when I took it out the sidebar transition is butter smooth and not nearly so "instant".
{openDrawer && (
<SwipeableDrawer
disableBackdropTransition={!iOS}
disableDiscovery={iOS}
open={openDrawer}
onOpen={() => setOpenDrawer(true)}
onClose={() => setOpenDrawer(false)}
>
<ListItem>
<ListItemText>hello</ListItemText>
<br />
<ListItemText>hello</ListItemText>
</ListItem>
</SwipeableDrawer>
)}
Remove the conditional rendering.
<SwipeableDrawer
disableBackdropTransition={!iOS}
disableDiscovery={iOS}
open={openDrawer}
onOpen={() => setOpenDrawer(true)}
onClose={() => setOpenDrawer(false)}
>
<ListItem>
<ListItemText>hello</ListItemText>
<br />
<ListItemText>hello</ListItemText>
</ListItem>
</SwipeableDrawer>
I'm trying to use Material UI's drawer component (https://material-ui.com/components/drawers/) to set up a navigation bar. As I'm using this code for the project, I'm not sure exactly how to link the href properly so the user can click on the home menu button and routes to a different page. I have used history.push in each function for different pages I have created, but not sure how to link it up.
import React, { useEffect, useState } from 'react'
import { makeStyles } from '#material-ui/core/styles';
import { Drawer, Button, List, Divider, ListItem, ListItemIcon, ListItemText, AppBar, IconButton, Toolbar, Typography, Collapse } from '#material-ui/core';
import { Link } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import clsx from 'clsx';
import SortIcon from '#material-ui/icons/Sort';
import ExpandMoreIcon from '#material-ui/icons/ExpandMore';
import InboxIcon from '#material-ui/icons/MoveToInbox';
import MailIcon from '#material-ui/icons/Mail';
import HomeIcon from '#material-ui/icons/Home';
import LockOpenIcon from '#material-ui/icons/LockOpen'; // log in
import ExitToAppIcon from '#material-ui/icons/ExitToApp'; // sign out
import AccountCircleIcon from '#material-ui/icons/AccountCircle'; //user profile?
import GroupIcon from '#material-ui/icons/Group'; // team
import AccountBoxIcon from '#material-ui/icons/AccountBox';
import wecycle from '../images/wecycle_logo.PNG';
const useStyles = makeStyles((theme) => ({
main: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
/*height: "100vh",*/
fontFamily: "Roboto",
},
navbar: {
backgroundColor: "white",
},
navbarContent: {
width: "100%",
margin: "0 auto",
},
navbarTitle: {
fontSize: "2rem",
flexGrow: '2',
},
icon: {
color: 'black',
fontSize: "2rem",
},
colorText: {
color: "#5AFF3D",
},
container: {
textAlign: "center",
},
title: {
color: "#fff",
fontSize: "2.5rem",
},
list: { //NEW
width: 250,
},
fullList: {
width: 'auto',
},
wecycleLogo: {
width: "115px",
height: "50px",
}
}));
/**
* The code line 63 to 147 is composed of Material UI Drawer Component code.
* Please refer to https://material-ui.com/components/drawers/ for 'Temporary Drawer'
*
* #returns header
*/
export default function Header() {
const classes = useStyles();
const {currentUser, logout } = useAuth();
const [error, setError] = useState("");
const history = useHistory();
function aboutUsRedirect() {
history.push("/aboutUs");
}
function landingRedirect() {
history.push("/");
}
function loginRedirect() {
history.push("/login");
}
function signupRedirect() {
history.push("/signup");
}
async function handleLogout() {
setError('');
try {
await logout();
history.pushState("/");
} catch {
setError("Failed to log out");
}
}
const [state, setState] = React.useState({
right: false,
});
const toggleDrawer = (anchor, open) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setState({ ...state, [anchor]: open });
};
const list = (anchor) => (
<div
className={clsx(classes.list, {
[classes.fullList]: anchor === 'top' || anchor === 'bottom',
})}
role="presentation"
onClick={toggleDrawer(anchor, false)}
onKeyDown={toggleDrawer(anchor, false)}
>
<List>
{['Home', 'Log In', 'Sign Up'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <HomeIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{['Profile', 'About'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <AccountBoxIcon /> : <GroupIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</div>
);
return (
<div className={classes.main} id="header">
<AppBar className={classes.navbar}>
<Toolbar className={classes.navbarContent}>
<h1 className={classes.navbarTitle}>
<img src = {wecycle} className={classes.wecycleLogo} />
</h1>
<IconButton>
{['right'].map((anchor) => (
<React.Fragment key={anchor}>
<IconButton onClick={toggleDrawer(anchor, true)}>
<SortIcon className={classes.icon} />
</IconButton>
<Drawer anchor={anchor} open={state[anchor]} onClose={toggleDrawer(anchor, false)}>
{list(anchor)}
</Drawer>
</React.Fragment>
))}
</IconButton>
</Toolbar>
</AppBar>
</div>
);
}
You can attach the callbacks to the ListItem component.
<ListItem button onClick={clickHandler}>
<ListItemIcon>
<IconComponent />
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
You can optimize your item mapping by moving more data into the array being mapped.
const menuItems = [
{
text: 'Home',
icon: HomeIcon,
onClick: () => history.push("/"),
},
{
text: 'Log In',
icon: MailIcon,
onClick: () => history.push("/login"),
},
{
text: 'Sign Up',
icon: HomeIcon,
onClick: () => history.push("/signup"),
},
];
...
<List>
{menuItems.map(({ text, icon: Icon, onClick}, index) => (
<ListItem button key={text} onClick={onClick}>
<ListItemIcon>
<Icon />
</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
I have a component called Comment List, comment list is getting all comments that is apart of this.props.posts Which comes from the dashboard container.
The <CommentList/> component is being called in the <PostList/> component, from there it is passing {post.Comments} as props to
My question is how would i properly test <CommentList/> Component, considering it relies on redux selector, api call etc.
Here is the flow.
1) dashboard container holds the props for this.props.post
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
addContent,
addTitle,
createPostInit,
deleteCommentInit,
initCommentUpdates,
deletePostInit,
dislikePostInit,
getPostsInit,
likePostInit,
notificationInit,
postCommentInit,
} from "../actions/postActions";
import Dashboard from "../components/dashboard/dashboard";
import { getBodyError, getIsNotified, getNotification, getPopPosts, getPosts, getTitleError, getUser, postContent, title } from "./../selectors/selectors";
const mapDispatchToProps = (dispatch: any) => ({
getPostsInit: () => dispatch(getPostsInit()),
initCommentUpdates: () => dispatch(initCommentUpdates()),
notificationInit: () => dispatch(notificationInit()),
likePost: (id: number) => dispatch(likePostInit(id)),
addTitle: (data: string) => dispatch(addTitle(data)),
addContent: (data: string) => dispatch(addContent(data)),
postCommentInit: (commentData: object) => dispatch(postCommentInit(commentData)),
dislikePost: (id: number) => dispatch(dislikePostInit(id)),
deletePostInit: (id: number, userId: number) => dispatch(deletePostInit(id, userId)),
deleteComment: (id: number, postId: number, userId: number) => dispatch(deleteCommentInit(id, postId, userId)),
createPostInit: (postData: object) => dispatch(createPostInit(postData)),
});
const mapStateToProps = createStructuredSelector({
posts: getPosts(),
popPosts: getPopPosts(),
user: getUser(),
isNotified: getIsNotified(),
titleError: getTitleError(),
bodyError: getBodyError(),
title: title(),
postContent: postContent(),
notification: getNotification(),
});
export default connect(mapStateToProps, mapDispatchToProps)(Dashboard);
this.props.posts gets mapped, and post.Commments gets passed to commentList prop
postList.tsx
{post.Comments.length > 0 ? (
<Fragment>
<Typography style={{ padding: "10px 0px", margin: "20px 0px" }}>Commments</Typography>
<CommentList user={currentUser} deleteComment={props.deleteComment} userId={post.userId} postId={post.id} comments={post.Comments} />
{/* if show more hide show more button and show show less comments button */}
</Fragment>
) : (
<Grid item={true} sm={12} lg={12} style={{ padding: "30px 0px" }}>
<Typography>No Commments Yet</Typography>
</Grid>
)}
CommentList.tsx
import Button from "#material-ui/core/Button";
import Divider from "#material-ui/core/Divider";
import Grid from "#material-ui/core/Grid";
import List from "#material-ui/core/List";
import ListItem from "#material-ui/core/ListItem";
import Typography from "#material-ui/core/Typography";
import OurListItem from "../../common/OurListItem";
import DeleteOutlineOutlinedIcon from "#material-ui/icons/DeleteOutlineOutlined";
import moment from "moment";
import React, { Fragment, useState } from "react";
export default function CommentList(props: any) {
const [showMore, setShowMore] = useState<Number>(3);
const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
const showComments = (e) => {
e.preventDefault();
setShowMore(12);
setShowLessFlag(true);
};
const showLessComments = (e) => {
e.preventDefault();
setShowMore(3);
setShowLessFlag(false);
};
return (
<Grid>
{props.comments.slice(0, showMore).map((comment, i) => (
<div key={i}>
<List style={{ paddingBottom: "20px" }}>
<OurListItem>
<Typography color="primary" align="left">
{comment.comment_body}
</Typography>
{comment.gifUrl && (
<div style={{ display: "block" }}>
<img width="100%" height="300px" src={`${comment.gifUrl}`} />
</div>
)}
</OurListItem>
{props.user && props.user.user && comment.userId === props.user.user.id ? (
<Typography style={{ display: "inline-block", float: "right" }} align="right">
<span style={{ cursor: "pointer" }} onClick={() => props.deleteComment(comment.id, props.postId, comment.userId)}>
<DeleteOutlineOutlinedIcon style={{ margin: "-5px 0px" }} color="primary" /> <span>Delete</span>
</span>
</Typography>
) : null}
<Typography style={{ padding: "0px 0px" }} variant="caption" align="left">
{comment.author.username}
</Typography>
<Typography style={{ fontSize: "12px" }} variant="body1" align="left">
{moment(comment.createdAt).calendar()}
</Typography>
<Divider variant="fullWidth" component="li" />
</List>
</div>
))}
<Fragment>
{props.comments.length > 3 && showLessFlag === false ? (
<Button onClick={(e) => showComments(e)} variant="outlined" component="span" color="primary">
Show More Comments
</Button>
) : (
<Fragment>
{props.comments.length > 3 && (
<Button onClick={(e) => showLessComments(e)} variant="outlined" component="span" color="primary">
Show Less Comments
</Button>
)}
</Fragment>
)}
</Fragment>
</Grid>
);
}
How would i correctly test this component with redux, considering im not getting it from redux, here is my approach,
CommentList.test.tsx
import React from "react";
import CommentList from "./CommentList";
import Grid from "#material-ui/core/Grid";
import { createShallow } from "#material-ui/core/test-utils";
import toJson from "enzyme-to-json";
const props = {
comments: [
{
userId: 1,
id: 1,
comment_body: "delectus aut autem",
author: {
username: "Bill",
},
},
{
userId: 2,
id: 2,
comment_body: "delectus aut autem",
author: {
username: "Bill",
},
},
{
userId: 3,
id: 3,
comment_body: "delectus aut autem",
author: {
username: "Bill",
},
},
],
};
describe("Should render <CommentList/>", () => {
let wrapper;
let shallow;
beforeEach(() => {
shallow = createShallow();
wrapper = shallow(<CommentList {...props} />);
});
it("should render <CommentList/>", () => {
expect(wrapper.find(Grid)).toHaveLength(1);
});
it("should snap <CommentList/> component", () => {
// expect(toJson(wrapper)).toMatchSnapshot();
});
});
My question is how would i properly test Component, considering it relies on redux selector, api call etc.
I don't see this being true anywhere. Component doesn't rely nor know about Redux, it's only getting props (which you can mock in your tests).
How would i correctly test this component with redux, considering I'm not getting it from redux, here is my approach
You don't - that's testing implementation details. You can test the reducers themselves, but the best way to test this is not to tie them together.
The way I see it, you're trying to test your reducers using this component, not necessarily the component itself as to test the component itself works just fine.
Or to test it all together, you should look at E2E tests.
How to change the content when clicked on different items.
I have two different archives (Home.js and Sidebar.js), in Sidebar I declare the items, but in Home, I put some buttons. But I don't know how to pass the information that I want to change between the items listed in my sidebar.
I am using this Drawer example (https://material-ui.com/demos/drawers/#persistent-drawer).
Project Running
in my app.js i have
import React, { Component } from 'react';
import Footer from './componets/Footer';
import Home from './componets/Home';
import store from './store'
import { Provider } from 'react-redux';
class App extends Component {
render() {
return (
<Provider store={store}>
<div className="content">
<Drawer/>
<Home/>
<Footer/>
</div>
</Provider>
);
}
}
export default App;
In my css file:
.conteudo{
display: grid;
grid-template-areas:
'home home home home'
'home home home home'
'footer footer footer footer'
}
I got a way to do it. But for every button in my drawer, i need to create a function that puts a number in my value. Have a way to declare one function and that every button in my class pass a number to my value?
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '#material-ui/core/styles';
import Drawer from '#material-ui/core/Drawer';
import CssBaseline from '#material-ui/core/CssBaseline';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import List from '#material-ui/core/List';
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 ListItem from '#material-ui/core/ListItem';
import ListItemIcon from '#material-ui/core/ListItemIcon';
import ListItemText from '#material-ui/core/ListItemText';
import Button from '#material-ui/core/Button'
import HomeIcon from '#material-ui/icons/Home'
import MeetingRoomIcon from '#material-ui/icons/MeetingRoom'
const drawerWidth = 240;
function Conteudo(props){
return(
<Typography component='div'>
{props.children}
</Typography>
)
}
Conteudo.propTypes ={
children: PropTypes.node.isRequired,
};
const styles = theme => ({
root: {
display: 'flex',
},
appBar: {
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
menuButton: {
marginLeft: 12,
marginRight: 20,
},
hide: {
display: 'none',
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
padding: '0 8px',
...theme.mixins.toolbar,
justifyContent: 'flex-end',
},
content: {
flexGrow: 1,
padding: theme.spacing.unit * 3,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
marginLeft: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
marginLeft: 0,
},
});
class PersistentDrawerLeft extends React.Component {
state = {
open: false,
value: 0
};
handleDrawerOpen = () => {
this.setState({ open: true });
};
handleDrawerClose = () => {
this.setState({ open: false });
};
checkEvent = () => {
this.setState({value : 1})
console.log({value : 1})
}
checkEvent1 = () => {
this.setState({value : 0})
console.log({value : 0})
}
handleChange = (event, value) => {
this.setState({ value })
console.log(value)
}
render() {
const { classes, theme } = this.props;
const { open } = this.state;
const { value } = this.state;
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
position="fixed"
className={classNames(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar disableGutters={!open}>
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={this.handleDrawerOpen}
className={classNames(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit" noWrap>
Drawer
</Typography>
</Toolbar>
</AppBar>
<Drawer
value ={value}
className={classes.drawer}
variant="persistent"
anchor="left"
open={open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<List>
<ListItem button onClick={this.checkEvent1} onChange={this.handleChange}>
<ListItemIcon>
<HomeIcon/>
</ListItemIcon>
<ListItemText primary='Central'/>
</ListItem>
<ListItem button onClick={this.checkEvent} onChange={this.handleChange}>
<ListItemIcon>
<MeetingRoomIcon/>
</ListItemIcon>
<ListItemText primary='BedRoom'/>
</ListItem>
</List>
<Divider />
</Drawer>
<main
className={classNames(classes.content, {
[classes.contentShift]: open,
})}
>
<div className={classes.drawerHeader} onChange={this.handleChange}/>
{value === 0 && <Conteudo> <Button variant="contained" color="primary">Default</Button> </Conteudo>}
{value === 1 && <Conteudo><Button variant="contained" color="secondary">Default</Button> </Conteudo>}
{value === 2 && <Conteudo><Button variant="contained" color="danger">Default</Button> </Conteudo>}
</main>
</div>
);
}
}
PersistentDrawerLeft.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default withStyles(styles, { withTheme: true })(PersistentDrawerLeft);