unable to set state in react for provided situation - javascript

i am building a ecommerce web app with react and i am unable to set state profileOptionsLayer when i click on the highlighted listitem both the logs are displayed on the console but component dosent rerender and state "profileOptionsLayer" is not updated either ,i am unable to locate the reason need help!
ALL imports .....
const TemporaryDrawer = ({
profileDrawerlayer,
setprofileDrawerlayer,
setuserDetails,
userDetails,
}) => {
const [profileOptionsLayer, setprofileOptionsLayer] = useState();
console.log(profileOptionsLayer);
return (
<>
<Drawer
anchor={"right"}
open={profileDrawerlayer}
onClose={() => {
setprofileDrawerlayer(false);
}}
>
<Box
sx={{ width: 250, background: "lightblue", height: "100%" }}
role="presentation"
onClick={() => {
setprofileDrawerlayer(false);
}}
onKeyDown={() => {
setprofileDrawerlayer(false);
}}
>
<List>
////////////////////////////////////// Below ///////////////////////////////////////////////
<ListItem disablePadding>
<ListItemButton
onClick={() => {
console.log("dsadsa");
setprofileOptionsLayer("View"); <= unable to set this state
console.log(profileOptionsLayer);
console.log("dsadsa");
}}
>
<ListItemIcon>
<VisibilityIcon />
</ListItemIcon>
<ListItemText primary={"View Profile"} />
</ListItemButton>
</ListItem>
/////////////////////////////////////// UP /////////////////////////////////////////
<ListItem
disablePadding
onClick={() => {
localStorage.removeItem("userId");
setuserDetails("");
}}
>
<ListItemButton>
<ListItemIcon>
<LogoutIcon />
</ListItemIcon>
<ListItemText primary={"Logout"} />
</ListItemButton>
</ListItem>
</List>
<Divider />
</Box>
</Drawer>
{profileOptionsLayer &&<ProfileOptions {...{ userDetails }} />}
</>
);
};
export default TemporaryDrawer;

Related

Implementing a Modal inside a Drawer in Material UI

I'm using Material UI and im trying to make a Modal pop up from a Responsive Drawer component. The problem is that when i click on the button, the Modal is rendered and instantly closed. I think that is because of the closing animation of the modal.
I tried a lot of workarounds, played with the z-index a little bit but nothing is working. Any ideas? This is the Modal code:
<div>
<Button
onClick={handleOpen}
sx={{
backgroundColor: "black",
color: "white",
borderBottom: "1px solid #f14d59",
borderRadius: "0px",
}}
>
Log In
</Button>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style} className="modal-box">
<button className="close-popup" onClick={handleClose}>
x
</button>
<Validations />
</Box>
</Modal>
</div>
and this is the Drawer:
const toggleDrawer = (anchor, open) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
}
setState({ ...state, [anchor]: open });
};
const list = (anchor) => (
<Box
sx={{
width: 250,
}}
role="presentation"
onClick={toggleDrawer(anchor, false)}
onKeyDown={toggleDrawer(anchor, false)}
>
<List>
{icons.map((icon) => (
<a to={icon.route} key={icon.title} href={icon.href}>
<ListItem disablePadding>
<ListItemButton>
<ListItemIcon sx={{ color: "#f14d59" }}>
<icon.icon />
</ListItemIcon>
<ListItemText
primary={icon.title}
sx={{ color: "#f14d59", fontWeight: "700" }}
/>
</ListItemButton>
</ListItem>
</a>
))}
</List>
<Divider sx={{ backgroundColor: "lightgrey" }} />
<List>
<ListItem disablePadding>
<ListItemButton>
<Modal />
</ListItemButton>
</ListItem>
</List>
</Box>
);
<nav>
<React.Fragment key={"left"}>
<Button onClick={toggleDrawer("left", true)}>
<MenuIcon sx={{ color: "white" }} />
</Button>
<Drawer
anchor={"left"}
open={state["left"]}
onClose={toggleDrawer("left", false)}
>
{list("left")}
</Drawer>
</React.Fragment>
</nav>

In MUI how can i add color to something inside of CardHeader?

I would like to change the colors of each title={note.title} subheader={note.category} I have tried
const theme = createTheme ({
palette: {
category: {
color: blue
}
}
})
But that hasn't worked I have also tried inline
sx={{fontSize: 16,color: '#000000'}} again no luck.
How can I go about editing the color for those 2 sections?
<div>
<Card elevation={10} className={classes.test}>
<CardHeader
action={ // 200
<IconButton onClick={() => handleDelete(note.id)}>
<DeleteOutlined />
</IconButton>
}
title={note.title}
subheader={note.category}
/>
<CardContent>
<FormGroup>
<FormControlLabel sx={{fontSize: 16,color: '#000000'}} control={<Checkbox />} label={note.details} />
<FormControlLabel sx={{fontSize: 16,color: '#555555'}} control={<Checkbox />} label={note.details2} />
</FormGroup>
</CardContent>
</Card>
</div>
)
Full code here : https://github.com/Orelso/Project-notes
You can pass node in the title and subheader -
<CardHeader
action={ // 200
<IconButton onClick={() => handleDelete(note.id)}>
<DeleteOutlined />
</IconButton>
}
title={<span style={{fontSize: 16, color: "#000000"}}>{note.title}</span>}
subheader={<span style={{fontSize: 12, color: "#000000"}}>{note.category}</span>}
/>

Use multiple checkbox to show/hide multiple input fields with React

For each checkbox i need to show/hide values in a dialog.
The code for adding and removing selecteditems is working.
How can I show each input after the checkbox with React hide/show for multiple fields?
The React is correct and if the second function is removed from the JS code this will work with the first checkbox and input... but, I don't know how to write the React code for multiple fields for this React structure.
Image
Here is the code
const [selectedItems, setSelectedItems] = React.useState<any>([]);
const handleToggle = (record: any) => () => {
const currentIndex = selectedItems.indexOf(record);
const newChecked = [...selectedItems];
if (currentIndex === -1) {
newChecked.push(record);
} else {
newChecked.splice(currentIndex, 1);
}
setSelectedItems(newChecked);
};
This is view
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
PaperProps={{
style: {
width: 500,
backgroundColor: "#222",
color: "white"
}
}}
maxWidth="lg"
>
<DialogContent>
<List sx={{ width: '100%', maxWidth: 500 }}>
{expensesType.map((record: any) => {
const labelId = `checkbox-list-label-${record.id}`;
return (
<ListItem
key={record}
secondaryAction={showInput(record)}
>
<ListItemButton role={undefined} onClick={handleToggle(record)} dense>
<ListItemIcon>
<Checkbox
edge="start"
checked={selectedItems.indexOf(record) !== -1}
tabIndex={-1}
value={record.value}
disableRipple
inputProps={{ 'aria-labelledby': labelId }}
/>
</ListItemIcon>
<ListItemText id={labelId} primary={record.name} />
</ListItemButton>
</ListItem>
);
})}
</List>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Cancel</Button>
<Button onClick={handleClose} autoFocus>
Done
</Button>
</DialogActions>
</Dialog>

Footer for page with Material-UI Drawer

So, there is a similar question on Stack Overflow, but that's not what I need. I want to make a regular full width footer at the bottom of the page. Here is the code for it, borrowed straight from Material-UI Drawer. Whatever I try to add here, I can't make my footer to appear at all. Once I managed to make it appear but it still was under the drawer, so I could only see a part of it to the right of the drawer.
const drawerWidth = 240;
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
display: 'flex',
},
appBar: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
},
drawer: {
width: drawerWidth,
flexShrink: 0,
},
drawerPaper: {
width: drawerWidth,
},
// necessary for content to be below app bar
toolbar: theme.mixins.toolbar,
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing(3),
},
}),
);
export default function PermanentDrawerLeft() {
const classes = useStyles();
return (
<div className={classes.root}>
<CssBaseline />
<AppBar position="fixed" className={classes.appBar}>
<Toolbar>
<Typography variant="h6" noWrap>
Permanent drawer
</Typography>
</Toolbar>
</AppBar>
<Drawer
className={classes.drawer}
variant="permanent"
classes={{
paper: classes.drawerPaper,
}}
anchor="left"
>
<div className={classes.toolbar} />
<Divider />
<List>
{['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
<Divider />
<List>
{['All mail', 'Trash', 'Spam'].map((text, index) => (
<ListItem button key={text}>
<ListItemIcon>{index % 2 === 0 ? <InboxIcon /> : <MailIcon />}</ListItemIcon>
<ListItemText primary={text} />
</ListItem>
))}
</List>
</Drawer>
<main className={classes.content}>
<div className={classes.toolbar} />
<Typography paragraph>
Text
</Typography>
<Typography paragraph>
Text
</Typography>
</main>
</div>
);
}

React and Material UI: how can I expand only one single card

I'm using React and Material UI in order to show some mapped cards mapped. When I try to expand a card, all the cards are expanded at the same time. I figured out that I have to pass an index inside my "handleExpandClick" function, but still not working. Maybe I did it some kind of typo.
I found this question Expand one card on click that regards the same problem, but seems not to be applied to my situation.
Here my piece of code:
const useStyles = makeStyles(theme => ({
card: {
maxWidth: 345,
marginBottom: 15
},
media: {
height: 0,
paddingTop: "56.25%" // 16:9
},
expand: {
transform: "rotate(0deg)",
marginLeft: "auto",
transition: theme.transitions.create("transform", {
duration: theme.transitions.duration.shortest
})
},
expandOpen: {
transform: "rotate(180deg)"
},
avatar: {
width: 90
},
root: {
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
"& > *": {
margin: theme.spacing(0.5)
}
},
list: {
width: 200
}
}));
const ItininerariesList = ({ itineraries, activities }) => {
const classes = useStyles();
const [expanded, setExpanded] = React.useState(false);
let path = window.location.pathname;
let currentId = path.substring(path.lastIndexOf("/") + 1);
const itinerariesPerCity = itineraries.filter(
itiner => itiner.city_id === currentId
);
const handleExpandClick = () => {
setExpanded(!expanded);
};
return (
<Fragment>
{itinerariesPerCity.map((itinerary, i) => (
<Card className={classes.card} key={itinerary._id}>
<CardHeader
avatar={
<Grid
container
direction="column"
justify="flex-start"
alignItems="center"
className={classes.avatar}
>
<Avatar
aria-label="user"
alt={itinerary.profile_name}
src={itinerary.profile_img}
>
<PersonIcon />
</Avatar>
<Typography variant="caption" component="p">
{itinerary.profile_name}
</Typography>
</Grid>
}
action={
<IconButton aria-label="settings">
<MoreVertIcon />
</IconButton>
}
title={itinerary.title}
subheader={itinerary.sub_title}
/>
<CardContent>
</CardContent>
<CardActions disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label="share">
<ShareIcon />
</IconButton>
<IconButton
className={clsx(classes.expand, {
[classes.expandOpen]: expanded
})}
onClick={() => handleExpandClick()}
aria-expanded={expanded}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expanded} timeout="auto" unmountOnExit>
<CardContent>
<ActivitiesList
activities={activities}
itineraryId={itinerary._id}
/>
</CardContent>
</Collapse>
</Card>
))}
</Fragment>
);
};
export default ItininerariesList;
Any suggestions or guidance would be greatly appreciated. Thank you in advance.
In the expand handler you indeed have to pass the index. And also use it in the state.
Something like it:
const [expandedId, setExpandedId] = React.useState(-1);
...
const handleExpandClick = (i) => {
setExpandedId(expandedId === i ? -1 : i);
};
...
<CardContent />
<CardActions disableSpacing>
<IconButton aria-label="add to favorites">
<FavoriteIcon />
</IconButton>
<IconButton aria-label="share">
<ShareIcon />
</IconButton>
<IconButton
onClick={() => handleExpandClick(i)}
aria-expanded={expandedId === i}
aria-label="show more"
>
<ExpandMoreIcon />
</IconButton>
</CardActions>
<Collapse in={expandedId === i} timeout="auto" unmountOnExit>
<CardContent>
<div>ActivitiesList</div>
</CardContent>
</Collapse>
Here is a working example: https://codesandbox.io/s/eloquent-sara-wswrn

Categories

Resources