Display the correct CardContent in it's DialogContent - reactjs

I'm trying intergrate an option to display the data of a Card it's Dialog, with there being multiple Cards.
Right now I'm getting all the data from Firebase and each record is being displayed in a Card. The problem is that the Dialog will only display the data of the last looped item in the map, not of the Card that I'm trying to display in the Dialog.
How can I get the corresponding data from a Card and put it in it's Dialog? E.g: I open the Dialog of the 4th Card and only the data of the 4th Card gets displayed
The code:
useEffect(() => {
const getEvents = async () => {
const data = await getDocs(eventsRef);
data.forEach((doc) => {
setEventList(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
})
};
getEvents();
}, [])
return (
<>
<div className="stepper-title" style={{textAlign: "center"}}>
<b><h1>Aankomende afspraken</h1></b><br></br><p>Prik een afspraak die jou intereseerd</p>
</div>
<div className="event-list-container">
{
eventList && eventList.map((item, index) => {
return (
<div key={item.id}>
<Card variant="outlined" sx={{ width: 250 }}>
<CardContent>
<Typography sx={{ fontSize: 14 }} color="text.secondary" gutterBottom>
{item.date}
</Typography>
<Typography variant="h5" component="div">
{item.occasion.title}
</Typography>
<Typography sx={{ mb: 1.5 }} color="text.secondary">
{item.location}
</Typography>
<Typography variant="body2">
{item.occasion.description}
</Typography>
</CardContent>
<CardActions>
card {index}
<Button onClick={handleClickOpen} size="small" itemID={item.id}>bekijken</Button>
<Dialog open={open} onClose={handleClose} PaperProps={{elevation: 1}} hideBackdrop>
<DialogContent>
<TextField
label="Titel"
defaultValue={eventList[index].occasion.title}
fullWidth
variant="standard"
/>
<TextField
label="Description"
defaultValue={eventList[index].occasion.description}
fullWidth
variant="standard"
/>
<TextField
label="Datum"
defaultValue={eventList[index].date}
fullWidth
variant="standard"
/>
<TextField
label="Locatie"
defaultValue={eventList[index].location}
fullWidth
variant="standard"
/>
<TextField
label="Naam"
defaultValue={eventList[index].organizer.name}
fullWidth
variant="standard"
/>
<TextField
label="E-mailadres"
defaultValue={eventList[index].organizer.email}
fullWidth
variant="standard"
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>terug</Button>
<Button onClick={handleClose}>Aanpassen</Button>
</DialogActions>
</Dialog>
</CardActions>
</Card>
</div>
)
})
}
</div>
</>
);

Related

How can I change the button color

Here in this one I have already declared the onClick but now I want to change the color of button whenever I click it should
<Button
className={classes.button_reset}
onClick={() => setShowResetPass((current) => !current)}
>
Reset Password
</Button>
<Button
sx={{ ml: "20px" }}
onClick={handleCancel}
className={classes.button_light}
>
Cancel
</Button>
<Grid md={6} xs={12}>
{showResetPass && (
<>
<Typography
color="#05445E"
fontFamily="'Jost', sans-serif"
fontSize={15}
sx={{ mt: "20px" }}
>
Enter New Password
</Typography>
<Input
className={classes.inputEmail}
fullWidth
type="password"
/>
</>
)}
This is the states I have used
const [showResetPass, setShowResetPass] = useState(false);
You could do something like that:
<Button
sx={{ ml: "20px" }}
onClick={handleCancel}
className={showResetPass ? classes.button_light : classes.button_dark }
>

Why come card content is not showing in MUI

import React from "react";
import {
Card,
CardActions,
CardContent,
Button,
CardMedia,
Typography,
} from "#mui/material";
import ThumbUpAlt from "#mui/icons-material/ThumbUpAlt";
import Delete from "#mui/icons-material/Delete";
import MoreHoriz from "#mui/icons-material/MoreHoriz";
import moment from "moment";
import useStyles from "./styles";
const Post = ({ post }) => {
const classes = useStyles();
return (
<Card className={classes.card}>
<CardMedia
className={classes.media}
image={post.selectedFile}
title={post.title}
>
<div className={classes.overlay}>
<Typography variant="h6">{post.creator}</Typography>
<Typography variant="body2">
{moment(post.createdAt).fromNow()}
</Typography>
</div>
// till here the card is showing
<div className={classes.overlay2}>
<Button style={{ color: "white" }} size="small" onClick={() => {}}>
<MoreHoriz fontSize="default" />
</Button>
</div>
<div className={classes.details}>
<Typography variant="body2" color="textSecondary">
{post.tags.map((tag) => `#${tag}`)}
</Typography>
</div>
<CardContent>
<Typography className={classes.title} variant="h5" gutterBottom>
{post.message}
</Typography>
</CardContent>
<CardActions className={classes.cardActions}>
<Button size="small" color="primary" onClick={() => {}}>
<ThumbUpAlt fontSize="small" />
Like
{post.likeCount}
</Button>
<Button size="small" color="primary" onClick={() => {}}>
<Delete fontSize="small" />
Delete
</Button>
</CardActions>
</CardMedia>
</Card>
);
};
export default Post;
I'm passing data from parent to child as a prop.After this i'm mapping the prop in card.But the issue is card is only showing till classes.overlay afterwards nothing is showing.Also code is not showing in inspect.I don't know what the issue is as i'm new to MUI.
May i know what the issue is so that i can fix it
Is because you are wrapping your component inside the CardMedia tags, when it should be a self-closing tag, so your code should look like this:
const Post = ({ post }) => {
const classes = useStyles();
return (
<Card className={classes.card}>
<CardMedia
className={classes.media}
image={post.selectedFile}
title={post.title}
/> // <--- This is the change
<div className={classes.overlay}>
<Typography variant="h6">{post.creator}</Typography>
<Typography variant="body2">
{moment(post.createdAt).fromNow()}
</Typography>
</div>
<div className={classes.overlay2}>
<Button style={{ color: "white" }} size="small" onClick={() => {}}>
<MoreHoriz fontSize="default" />
</Button>
</div>
<div className={classes.details}>
<Typography variant="body2" color="textSecondary">
{post.tags.map((tag) => `#${tag}`)}
</Typography>
</div>
<CardContent>
<Typography className={classes.title} variant="h5" gutterBottom>
{post.message}
</Typography>
</CardContent>
<CardActions className={classes.cardActions}>
<Button size="small" color="primary" onClick={() => {}}>
<ThumbUpAlt fontSize="small" />
Like
{post.likeCount}
</Button>
<Button size="small" color="primary" onClick={() => {}}>
<Delete fontSize="small" />
Delete
</Button>
</CardActions>
</Card>
);
};
export default Post;

React and LocalStorage

I am trying this code where I can send some data and save it in the localstorage. I tied the below code.
function Login () {
const uname=useRef()
const pass = useRef()
const getEmail = localStorage.getItem("emailData")
const getPassword = localStorage.getItem("passwordData")
const handleSubmit=()=>{
if(uname.current.value==="admin"&&pass.current.value==="admin"){
localStorage.setItem("emailData","admin")
localStorage.setItem("passwordData","admin")
}
}
const [values, setValues] = useState({
email: "",
pass: "",
showPass: false,
});
const handlePassVisibilty = () => {
setValues({
...values,
showPass: !values.showPass,
});
};
return (
<div>
{
getEmail&&getPassword?<Home/>:
<Container maxWidth="sm">
<Grid
container
spacing={2}
direction="column"
justifyContent="center"
style={{ minHeight: "100vh" }}
>
<Paper elelvation={2} sx={{ padding: 10 }}>
<h2>Welcome to Employee Management System</h2>
<form onSubmit={handleSubmit}>
<Grid container direction="column" spacing={2}>
<Grid item>
<TextField
type="text"
fullWidth
label="Enter your Username"
placeholder="Username"
variant="outlined"
required
ref={uname}
/>
</Grid>
<Grid item>
<TextField
type={values.showPass ? "text" : "password"}
fullWidth
label="Enter your Password"
placeholder="Password"
variant="outlined"
required
ref={pass}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handlePassVisibilty}
aria-label="toggle password"
edge="end"
>
{values.showPass ? (
<VisibilityOffIcon />
) : (
<VisibilityIcon />
)}
</IconButton>
</InputAdornment>
),
}}
/>
</Grid>
<Grid item>
<Button type="submit" fullWidth variant="contained" >
Sign In
</Button>
</Grid>
</Grid>
</form>
</Paper>
</Grid>
</Container>
}
</div>
);
};
export default Login;
What I am trying to do is that if the localstorage has the correct username and password the login page will redirect to the home page. The problem I am facing is that the data is not stored in the localstorage. Can someone please explain to me what I am doing wrong? Any help is appreciated Thank you.
you need to give type="submit" to button of your form in order to submit form
<Button fullWidth type="submit" variant="contained">
Sign In
</Button>
if it still not working, use state instead
here what I did with your code :
const getEmail = localStorage.getItem("emailData")
const getPassword = localStorage.getItem("passwordData")
const [values, setValues] = useState({
email: "",
pass: "",
showPass: false,
});
const handleSubmit=()=>{
if(values.email ==="admin" && values.pass ==="admin"){
localStorage.setItem("emailData","admin")
localStorage.setItem("passwordData","admin")
}
}
const handlePassVisibilty = () => {
setValues({
...values,
showPass: !values.showPass,
});
};
return (
<div>
{
getEmail&&getPassword?<Home/>:
<Container maxWidth="sm">
<Grid
container
spacing={2}
direction="column"
justifyContent="center"
style={{ minHeight: "100vh" }}
>
<Paper elelvation={2} sx={{ padding: 10 }}>
<h2>Welcome to Employee Management System</h2>
<form onSubmit={handleSubmit}>
<Grid container direction="column" spacing={2}>
<Grid item>
<TextField
type="text"
fullWidth
label="Enter your Username"
placeholder="Username"
variant="outlined"
required
value={values.email}
onChange={(e)=>{
setValues(prevState=>({...prevState,email:e.target.value}))
}}
/>
</Grid>
<Grid item>
<TextField
type={values.showPass ? "text" : "password"}
fullWidth
label="Enter your Password"
placeholder="Password"
variant="outlined"
required
value={values.pass}
onChange={(e)=>{
setValues(prevState=>({...prevState,pass:e.target.value}))
}}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handlePassVisibilty}
aria-label="toggle password"
edge="end"
>
{values.showPass ? (
<VisibilityOffIcon />
) : (
<VisibilityIcon />
)}
</IconButton>
</InputAdornment>
),
}}
/>
</Grid>
<Grid item>
<Button type="submit" fullWidth variant="contained" >
Sign In
</Button>
</Grid>
</Grid>
</form>
</Paper>
</Grid>
</Container>
}
</div>
);

How to add fields on the base of number of values from select menu in react js?

Here I want to pass the value from the select menu once I select the menu which has value 1, it must show only one array of objects but when I select menu 4 then it must show 4 arrays of objects or 4 times the same fields which I have, so kindly help me out of this problem, all are one component
import React from 'react'
import Box from '#mui/material/Box';
import Typography from '#mui/material/Typography';
import InputLabel from '#mui/material/InputLabel';
import FormControl from '#mui/material/FormControl';
import NativeSelect from '#mui/material/NativeSelect';
import TextField from '#mui/material/TextField';
import MenuItem from '#mui/material/MenuItem';
import Select from '#mui/material/Select';
const CourseScheduleStep4 = () => {
const [Session, setVal] = React.useState([]);
// const handleChange = (event) => {
// setVal(event.target.value);
// };
const [inputList, setInputList] = React.useState([{ class_date:"", class_start_time:"",class_end_time:"" }])
const handleAddinput = (e) => {
var count =e.target.value
//console.log(e.target.value)
setInputList([...inputList, [{ class_date:"" ,class_start_time:"" ,class_end_time:"" }]]);
console.log(inputList ,"inputList")
};
return (
<Box>
<Box className="my-4">
<Typography variant="h3" gutterBottom component="div" className="mb-0"> Set up your class schedule</Typography>
<Typography variant="subtitle1" gutterBottom component="div" className="mb-0">Let your students know when the class will take place so they can plan accordingly</Typography>
</Box>
<Box ClassName="StepsForm">
<FormControl className="selectDropdown w-100 mb-2">
<InputLabel shrink htmlFor="student-name" className="studentNameLabel">
How many Classes in this Course?
</InputLabel>
<Select sx={{ mb: 1 }}
onChange={(e)=>handleAddinput(e)}
displayEmpty
className="StepsFields"
inputProps={{ 'aria-label': 'Without label' }}
>
<MenuItem value={1} className="d-block p-2">1</MenuItem>
<MenuItem value={2} className="d-block p-2">2</MenuItem>
<MenuItem value={3} className="d-block p-2">3</MenuItem>
<MenuItem value={4} className="d-block p-2">4</MenuItem>
</Select>
</FormControl>
{/*Here I want to add value as per the selected number of values and add that much inputList */}
{inputList?.map((x,i)=>(
<Box className="SessionClassDetails mb-2">
<Typography variant="h6" gutterBottom component="div" className="CourseHeadingss">CLASS SESSION {i} </Typography>
<FormControl variant="standard" className="w-100 my-2">
<InputLabel shrink htmlFor="student-name" className="studentNameLabel">
Class Date
</InputLabel>
<TextField sx={{ mb: 1 }}
required
fullWidth
name="class_date"
id="name"
type="date"
variant="standard"
placeholder="Please Select"
className="StepsFields"
value={x.class_date}
/>
</FormControl>
<FormControl variant="standard" className="w-100 my-2">
<InputLabel shrink htmlFor="student-name" className="studentNameLabel">
Class Start Time
</InputLabel>
<TextField sx={{ mb: 1 }}
required
fullWidth
name="class_start_time"
id="name"
type="time"
variant="standard"
placeholder="Please Select"
className="StepsFields"
value={x.class_start_time}
/>
</FormControl>
<FormControl variant="standard" className="w-100 my-2">
<InputLabel shrink htmlFor="student-name" className="studentNameLabel">
Class End Time
</InputLabel>
<TextField sx={{ mb: 1 }}
required
fullWidth
name="class_end_time"
id="name"
type="time"
variant="standard"
placeholder="Please Select"
className="StepsFields"
value={x.class_end_time}
/>
</FormControl>
</Box>
))}
<FormControl variant="standard" className="w-100 my-2">
<InputLabel shrink htmlFor="student-name" className="studentNameLabel">
Price per Student
</InputLabel>
<TextField sx={{ mb: 1 }}
required
fullWidth
name="name"
id="name"
type="text"
variant="standard"
placeholder="$ 30.00"
className="StepsFields"
/>
</FormControl>
<Box>
<Typography variant="caption" display="block" gutterBottom align='right' className="SubText policyInstructions"> *Subject to the sites cancellation policy.</Typography>
</Box>
</Box>
</Box>
)
}
export default CourseScheduleStep4
Try this
const handleAddinput = (e) => {
var count = e.target.value;
const currentLength = inputList.length;
if (currentLength) {
let newList = [];
[...Array(count).keys()].forEach(() => {
[...inputList].forEach(i => {
newList.push({ ...i });
})
})
setInputList(newList);
} else {
setInputList([...Array(count).keys()].map(i => ({ class_date: "" , class_start_time: "" , class_end_time:"" })));
}
};

TypeError: Cannot read property 'tipodecontato' of undefined

Good afternoon folks I'm having problems executing the action of displaying my modal follows the error
https://ibb.co/WtdvbCC
Below is my code
const of modal
const [contatoAtualizado, setContatoAtualizado] = useState<IContatos>(dados as IContatos);
useEffect(() => {
if(dados !== undefined){
setContatoAtualizado(dados)
}
}, [dados, contatoAtualizado]);
const para abrir a modal
const handleOpen = () => {
setOpen(true);
};
button open a modal
<Button
color="primary"
startIcon={<Icon fontSize="small">add_circle</Icon>}
onClick={handleOpen}
>
Adicionar registro
</Button>
modal
<Dialog fullWidth open={true}>
<DialogTitle>Adicionar profissão</DialogTitle>
<DialogContent>
<Grid container spacing={2}>
<Grid item lg={6}>
<Box my={1}>
<FormLabel
htmlFor="tipodecontato"
children={"Tipo de contato"}
required={true}
/>
<Select
fullWidth
id="tipodecontato"
name="tipodecontato"
variant="outlined"
value={contatoAtualizado.tipodecontato}
onChange={(e) =>
setContatoAtualizado({
...contatoAtualizado,
tipodecontato: e.target.value as string,
})
}
>
{tipodeContato.map((item, index) => (
<MenuItem key={index} value={item.name}>
{item.name}
</MenuItem>
))}
</Select>
</Box>
</Grid>
<Grid item lg={6}>
<Box my={1}>
<FormLabel
htmlFor="informacaoProfissional"
children={"Informação profissional"}
/>
<Select
fullWidth
id="informacaoProfissional"
name="informacaoProfissional"
variant="outlined"
value={contatoAtualizado.informacaoProfissional}
onChange={(e) =>
setContatoAtualizado({
...contatoAtualizado,
informacaoProfissional: e.target.value as string,
})
}
>
{informacaoProfissional.map((item, index) => (
<MenuItem key={index} value={item.name}>
{item.name}
</MenuItem>
))}
</Select>
</Box>
</Grid>
</Grid>
<Grid container>
<Grid item lg={12}>
<Box my={1}>
<FormLabel
htmlFor="contato"
children={"Contato"}
required={true}
/>
<TextField
required
fullWidth
id="contato"
name="contato"
placeholder="Digite aqui"
variant="outlined"
margin="none"
value={contatoAtualizado.contato}
onChange={(e) => {
setContatoAtualizado({
...contatoAtualizado,
contato: e.target.value,
});
}}
/>
</Box>
</Grid>
</Grid>
<Grid container>
<Grid item lg={12}>
<Box my={1}>
<FormLabel htmlFor="observacao" children={"Observação"} />
<TextField
required
fullWidth
placeholder="Digite aqui"
id="observacao"
name="observacao"
variant="outlined"
margin="none"
value={contatoAtualizado.observacao}
onChange={(e) => {
setContatoAtualizado({
...contatoAtualizado,
observacao: e.target.value,
});
}}
/>
</Box>
</Grid>
</Grid>
</DialogContent>
<DialogActions>
<Button variant="outlined" color="primary" onClick={onClose}>
Cancelar
</Button>
<Button
variant="contained"
color="primary"
onClick={() => {
onSave(contatoAtualizado);
//console.log(contatoAtualizado)
}}
>
Confirmar
</Button>
</DialogActions>
</Dialog>
in this case I'm importing the modal to another component and opening it through the other component

Resources