How to select specific items using checkbox? - javascript

Assignment details are being fetched and shown in different cards. How can I implement select specific cards feature for getting their data and later on publish those selected cards. I'm putting my code picture and a reference picture.
Reference picture
Actual screen
Code
/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from 'react';
import {
Box, Grid, Typography, IconButton,
} from '#mui/material';
import { useDispatch, useSelector } from 'react-redux';
import { FormikProvider, useFormik } from 'formik';
import { useTranslation } from 'react-i18next';
import AddIcon from '#mui/icons-material/Add';
import DeleteForeverOutlinedIcon from '#mui/icons-material/DeleteForeverOutlined';
import DriveFileRenameOutlineOutlinedIcon from '#mui/icons-material/DriveFileRenameOutlineOutlined';
import RemoveRedEyeOutlinedIcon from '#mui/icons-material/RemoveRedEyeOutlined';
import Card from '#mui/material/Card';
import CardActions from '#mui/material/CardActions';
import CardContent from '#mui/material/CardContent';
import TextField from '#mui/material/TextField';
import { red } from '#mui/material/colors';
import styles from './styles';
import CheckboxAtom from '../../../../components/atoms/checkbox';
import useStyles from '../../../../custom-hooks/useStyles';
import Dropdown from '../../../../components/atoms/dropdown';
import DropdownWithLabel from '../../../../components/atoms/dropdown-with-label';
import ButtonAtom from '../../../../components/atoms/button';
import { Buttons } from '../../../../constant';
import { DialogAtom } from '../../../../components/atoms';
import DatePicker from '../../../../components/atoms/datepicker';
import { getclassesTimings } from '../../../../store/actions/getTeacherView';
import { getClassDetails } from '../../../teacher-user/attendance/helper';
const COURSE_OPTIONS = [
{ id: 'C1', key: 'Course1' },
{ id: 'C2', key: 'Course2' },
{ id: 'C3', key: 'Course3' },
];
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
const CARDS = [
{
id: 'k1',
key: 'Card1',
title: 'ASD',
createdAt: today.toDateString(),
createdBy: 'User1',
questions: [
{
Qname: 'Balabadi-5',
questionBody: [],
},
{
Qname: 'Balabadi 1-Q1',
questionBody: [
'askfhbjksadbnc?', 'askjjkasbcasc?',
],
},
],
},
{
id: 'k2',
key: 'Card2',
title: 'DSDF',
createdAt: today.toDateString(),
createdBy: 'User2',
questions: [
{
Qname: 'Balabadi 1-Q1',
questionBody: [],
},
// {
// Qname: 'Balabadi 1-Q1',
// questionBody: [
// 'askfhbjksadbnc?', 'askjjkasbcasc?',
// ],
// },
],
},
];
// const
const getCurrentAcademicYear = () => {
const currentYear = new Date().getFullYear();
const nextYear = new Date().getFullYear() + 1;
const currentAcademicYear = `${currentYear}-${nextYear}`;
return currentAcademicYear;
};
const getCourseOptions = (courses) => courses.map((course) => ({
id: course.id,
name: course.name,
}));
function OldAssignment({ courses }) {
const classes = useStyles(styles)();
const { t } = useTranslation();
const dispatch = useDispatch();
const reduxClass = useSelector((state) => state?.getTeacherView);
const events = reduxClass?.classesTimings;
const [eventsClassData, setEventsClassData] = useState([]);
const [selectedCourse, setSelectedCourse] = useState('');
const [issetAddAssignmentOpen, setAddAssignmentOpen] = useState(false);
const [ischecked, setIsChecked] = useState(false);
const courseOptions = courses.length ? getCourseOptions(courses) : [];
const handleCheck = (e) => {
setIsChecked(e.target.checked);
};
const onSubmit = (values) => {
// const {
// assignmentId, title, selectEvent, description, selectTopic, defaultScore, scheduledDate, attachResources,
// } = values;
// console.log(values);
// console.log({
// values,
// });
};
const formik = useFormik({
initialValues: {
assignmentId: '',
title: '',
selectEvent: '',
description: '',
selectTopic: '',
defaultScore: '',
scheduledDate: null,
attachResources: null,
},
// eslint-disable-next-line no-undef
onSubmit,
});
const {
touched, handleSubmit, values, errors, setFieldValue, handleChange,
} = formik;
// useEffect(() => {
// console.log(newAssignment);
// console.log(oldAssignment);
// });
useEffect(() => {
if (!selectedCourse) {
return;
}
const payload = {
courseId: selectedCourse,
academicYear: getCurrentAcademicYear(),
};
dispatch(getclassesTimings(payload));
}, [selectedCourse]);
useEffect(() => {
if (!events || !events.length) {
return;
}
setEventsClassData(getClassDetails(events));
}, [events]);
useEffect(() => {
if (!eventsClassData.length) {
return;
}
formik.setFieldValue('selectEvent', eventsClassData[0]?.id || '');
}, [eventsClassData]);
useEffect(() => {
if (!courseOptions || !courseOptions.length) {
return;
}
setSelectedCourse(courseOptions[0]?.id || '');
}, [courseOptions]);
// const handleSubmit = (values) => {
// return ({
// console,: .log(values)
// });
// }
const renderAddFolderContent = () => (
<Grid className={classes.addDialog}>
<FormikProvider value={formik}>
<Box
component="form"
sx={{
'& .MuiTextField-root': { m: 1, width: '10vw' },
}}
noValidate
autoComplete="off"
>
<Grid container spacing={2} sx={{ display: 'flex' }}>
<Grid item>
<TextField
className={classes.popupTextField}
required
id="outlined-required"
label="Assignment Id"
// value={isAddFolderName}
// onChange={(e) => setAddFolderName(e.target.value)}
defaultValue={formik.values.assignmentId}
name="assignmentId"
// onChange={(e) => setFieldValue('assignmentId', e.target.value)}
onChange={formik.handleChange}
/>
</Grid>
<Grid item>
<TextField
className={classes.popupTextField}
required
id="outlined-required"
label="Title"
// value={isAddFolderName}
// onChange={(e) => setAddFolderName(e.target.value)}
name="title"
value={formik.values.title}
onChange={formik.handleChange}
/>
</Grid>
<Grid item sx={{ minWidth: '13vw' }}>
<DropdownWithLabel
id="selectEvent"
name="selectEvent"
disabled={false}
options={eventsClassData}
// label={`${t('COURSES')}`}
label="Select Event"
placeholder="Select Event"
customStyles={classes.dropDownCont}
handleChange={formik.handleChange}
value={formik.values.selectEvent}
/>
</Grid>
<Grid item>
<TextField
className={classes.popupTextField}
required
id="outlined-required"
label="Description"
name="description"
// value={isAddFolderName}
// onChange={(e) => setAddFolderName(e.target.value)}
defaultValue={formik.values.description}
value={formik.values.description}
onChange={formik.handleChange}
/>
</Grid>
</Grid>
<Grid container spacing={2} sx={{ display: 'flex', marginTop: '10px' }}>
<Grid item sx={{ minWidth: '13vw' }}>
<DropdownWithLabel
id="selectTopic"
name="selectTopic"
disabled={false}
options={
COURSE_OPTIONS.map((course) => ({
id: course.id,
name: course.key,
}))
}
// label={`${t('COURSES')}`}
label="Select Topic"
handleChange={formik.handleChange}
value={formik.values.selectTopic}
/>
</Grid>
<Grid item>
<TextField
className={classes.popupTextField}
required
id="outlined-required"
label="Default Score"
name="defaultScore"
// value={isAddFolderName}
// onChange={(e) => setAddFolderName(e.target.value)}
defaultValue={formik.values.defaultScore}
onChange={formik.handleChange}
/>
</Grid>
<Grid item>
<div className={classes.datePickerWrapper}>
<DatePicker
style={{ padding: '0px !important' }}
required
/>
</div>
</Grid>
<Grid item>
<TextField
className={classes.popupTextField}
required
id="outlined-required"
label="Attach Resources"
// value={isAddFolderName}
// onChange={(e) => setAddFolderName(e.target.value)}
defaultValue={formik.values.attachResources}
name="attachResources"
/>
</Grid>
</Grid>
</Box>
<Grid item xs={12} sx={{ display: 'flex', justifyContent: 'flex-end', marginTop: '10px' }}>
<ButtonAtom
className={classes.popupBtn}
name={t('CANCEL')}
// onClick={() => setAddFolderOpenDialog(false)}
btntype={Buttons.SECONDARY}
/>
<ButtonAtom
className={classes.popupBtn}
name={t('ADD')}
btntype={Buttons.PRIMARY}
type="submit"
// onclick={() => console.log('skjbdaskjhbd')}
onClick={handleSubmit}
/>
</Grid>
</FormikProvider>
</Grid>
);
return (
<Box container>
<DialogAtom
isOpen={issetAddAssignmentOpen}
dialogHeading={t('ADD_ASSIGNMENT')}
customClass={classes.DialogAtom}
content={renderAddFolderContent()}
secHandle={() => setAddAssignmentOpen(false)}
/>
<Box className={classes.topContainerBox}>
<Grid item className={classes.headerGridItem}>
<div>
<Typography className={classes.headerTitle}>
{t('OLD_ASSIGNMENT')}
</Typography>
</div>
</Grid>
<Grid item className={classes.functionalGridItem}>
<div className={classes.dropdownDiv}>
{/* <DropdownWithLabel
id="courses"
name="courses"
disabled={false}
options={courseOptions}
label={`${t('COURSES')}`}
placeholder="COURSES"
customStyles={classes.dropDownCont}
value={selectedCourse}
handleChange={(e) => {
const { val } = e.target;
setSelectedCourse(val);
}}
/> */}
<ButtonAtom
className={classes.popupBtn}
name={t('CANCEL')}
// onClick={() => setAddFolderOpenDialog(false)}
btntype={Buttons.SECONDARY}
/>
</div>
<div className={classes.buttonDiv}>
<ButtonAtom
name={t('PUBLISH')}
onClick={() => { setAddAssignmentOpen(true); }}
btntype={Buttons.PRIMARY}
// icon={<AddIcon />}
/>
</div>
</Grid>
</Box>
<Box>
<Grid container spacing={2} className={classes.bottomGridContainer}>
{
CARDS.map((card) => {
return (
<Grid item>
<Card className={classes.mainCard}>
<Box className={classes.cardContainerBox}>
<Box className={classes.cardTopBox}>
<Grid
container
className={classes.firstGridContainer}
>
<Grid item>
<CardContent className={classes.zeroPadding}>
<Typography className={classes.cardTitleContainer}>
{card.title}
</Typography>
</CardContent>
</Grid>
<Grid item>
<Grid item>
<CardActions disableSpacing className={classes.zeroPadding}>
<CheckboxAtom
checked={ischecked}
handleChange={(e) => console.log(card.title)}
label=""
/>
</CardActions>
</Grid>
<Grid item />
</Grid>
</Grid>
<Grid conatiner className={classes.secondGridContainer}>
<CardContent className={classes.zeroPadding}>
<Typography variant="caption">
{card.createdAt}
</Typography>
</CardContent>
</Grid>
{/* <Grid
container
className={classes.thirdGridContainer}
>
<Grid item>
<CardContent className={classes.zeroPadding}>
<Typography variant="caption">
{card.createdBy}
</Typography>
</CardContent>
</Grid>
<Grid item>
<CardActions disableSpacing className={classes.zeroPadding}>
<IconButton aria-label="add to favorites" className={classes.zeroPadding}>
<RemoveRedEyeOutlinedIcon color="primary" />
</IconButton>
</CardActions>
</Grid>
</Grid> */}
</Box>
<hr />
<Box className={classes.cardBottomBox}>
{
card.questions.map((q) => {
return (
<Grid Conatiner className={classes.cardBottomGridContainer}>{q.Qname}</Grid>
);
})
}
</Box>
</Box>
</Card>
</Grid>
);
})
}
</Grid>
</Box>
</Box>
);
}
export default OldAssignment;
There are a lot of unnecessary code please ignore those, this is still under development.
<CheckboxAtom
checked={ischecked}
handleChange={(e) => console.log(card.title)}
label=""
/>
This is the checkbox.

Related

Object is Not a Function in firebase PhoneAuthentication

I am building a form where I have to login into the user by their phone number on CLICKING the send code button I got an error TypeError: Object(...) is not a function where it says that window is not a function can anybody solve my problem.
Error Image
Here is some of my code
import * as React from "react";
import { useState } from "react";
import Avatar from "#mui/material/Avatar";
import Button from "#mui/material/Button";
import ButtonGroup from "#mui/material/ButtonGroup";
import CssBaseline from "#mui/material/CssBaseline";
import TextField from "#mui/material/TextField";
import FormControlLabel from "#mui/material/FormControlLabel";
import Checkbox from "#mui/material/Checkbox";
import Link from "#mui/material/Link";
import Paper from "#mui/material/Paper";
import Box from "#mui/material/Box";
import Grid from "#mui/material/Grid";
import LockOutlinedIcon from "#mui/icons-material/LockOutlined";
import Typography from "#mui/material/Typography";
import { createTheme, ThemeProvider } from "#mui/material/styles";
import background from "../staticfiles/signin-background.jpg";
import "react-phone-input-2/lib/style.css";
import { auth, db, captcha } from "../config/Config";
import { RecaptchaVerifier } from "firebase/auth";
import { Link as RouterLink } from "react-router-dom";
import { useHistory } from "react-router-dom";
import socialMediaAuth from "../service/auth";
function Copyright(props) {
return (
<Typography
variant="body2"
color="text.secondary"
align="center"
{...props}
>
{"Copyright © "}
<Link color="inherit" href="https://mui.com/">
Your Website
</Link>{" "}
{new Date().getFullYear()}
{"."}
</Typography>
);
}
const theme = createTheme();
export default function SignInUserPhone() {
let history = useHistory();
const [PhoneNumber, setPhoenNumber] = useState("");
const [VerificationCode, setVerificationCode] = useState("");
const [error, setError] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
console.log(PhoneNumber);
console.log(error);
};
const handleSubmit2 = (e) => {
e.preventDefault();
console.log(VerificationCode);
};
const handleOnClick = async (provider) => {
const res = await socialMediaAuth(provider);
await db
.collection("SignedUpUsersData")
.doc(res.uid)
.set({
Email: res.email,
Name: res.displayName,
})
.then(() => {
history.push("/");
})
.catch((err) => setError(err.message));
};
const handleUserButton = (event) => {
event.preventDefault();
history.push("/signinuser");
};
const handleSellerButton = (event) => {
event.preventDefault();
history.push("/signinseller");
};
auth.languageCode = "it";
const setUpCaptcha = () => {
window.recaptchaVerifier = auth().RecaptchaVerifier("recaptcha-container", {
size: "invisible",
callback: (response) => {
// reCAPTCHA solved, allow signInWithPhoneNumber.
console.log(response);
console.log("Ok recapthca sloved");
onSignInSubmit();
},
});
};
const onSignInSubmit = (e) => {
e.preventDefault();
setUpCaptcha();
const phoneNumber = PhoneNumber;
const appVerifier = window.recaptchaVerifier;
auth()
.signInWithPhoneNumber(PhoneNumber, appVerifier)
.then((confirmationResult) => {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
console.log(confirmationResult);
// ...
})
.catch((error) => {
// Error; SMS not sent
// ...
console.log(error.message);
//( Or, if you haven't stored the widget ID:
});
};
return (
<ThemeProvider theme={theme}>
<Grid container component="main" sx={{ height: "100vh" }}>
<CssBaseline />
<Grid
item
xs={false}
sm={4}
md={7}
sx={{
backgroundImage: `url(${background})`,
backgroundRepeat: "no-repeat",
backgroundColor: (t) =>
t.palette.mode === "light"
? t.palette.grey[50]
: t.palette.grey[900],
backgroundSize: "cover",
backgroundPosition: "center",
}}
/>
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<Box
sx={{
my: 8,
mx: 4,
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in With Phone Number
</Typography>
<Box
sx={{
my: 4,
mx: 4,
display: "flex",
flexDirection: "column",
alignItems: "center",
}}
>
<ButtonGroup size="large" disableElevation variant="contained">
<Button onClick={handleSellerButton}>SELLER</Button>
<Button onClick={handleUserButton}>USER</Button>
</ButtonGroup>
</Box>
<Box
component="form"
noValidate
onSubmit={onSignInSubmit}
sx={{ mt: 1 }}
>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Phone Number"
name="Phone"
autoComplete="phoenumber"
value={PhoneNumber}
onChange={(phone) => setPhoenNumber(phone.target.value)}
/>
<div id="recaptcha-container"></div>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
onSubmit={onSignInSubmit}
id="sign-in-button"
>
Send Code
</Button>
<Grid container>
<Grid item xs></Grid>
<Grid item>
<Link
component={RouterLink}
to="/signup"
href="#"
variant="body2"
>
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</Box>
{error && <div>{error}</div>}
<Box
component="form"
noValidate
onSubmit={handleSubmit2}
sx={{ mt: 1 }}
>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Verification Code"
name="Verification"
autoComplete="Verification"
value={VerificationCode}
onChange={(verification) =>
setVerificationCode(verification.target.value)
}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
>
Submit
</Button>
<Copyright sx={{ mt: 5 }} />
</Box>
</Box>
</Grid>
</Grid>
</ThemeProvider>
);
}
All the files are correctly exported from config js cause sign in with email and password and sign in with social media are working
React uses a virtual DOM so doesn't have the same access to window as writing a website with pure javascript. So accessing the window object will often cause issues.
This does seem to be a duplicate of this answer though. That might help you fix the bug

withStyles Error to apply styles for elements using classes

Objects are not valid as a React child
(found: object with keys {$$typeof, render, propTypes, Naked, options, useStyles}).
If you meant to render a collection of children, use an array instead.
Code: codesandbox
const Form = () => {
//Input
const [project, setProject] = useState({
id: "",
name: "",
isPublic: false
});
const handleChange = (prop) => (event) => {
setProject({ ...project, [prop]: event.target.value });
};
const handlePermisson = (prop) => (event) => {
setProject({ ...project, [prop]: event.target.checked });
console.log(project);
};
const WithStyles = ({ classes }) => {
return (
<div>
<Grid container>
<Grid item md={6}>
<FormControl
className="classes.bottom-gap"
fullWidth
value={project.id}
onChange={handleChange("id")}
>
<TextField
id="project_id"
label="Project id"
variant="outlined"
/>
</FormControl>
<FormControl
fullWidth
value={project.name}
onChange={handleChange("name")}
>
<TextField
id="project_name"
label="Project name"
variant="outlined"
/>
</FormControl>
<FormControl
fullWidth
value={project.id}
onChange={handlePermisson("isPublic")}
>
<FormControlLabel control={<Switch />} label="Is Public" />
</FormControl>
</Grid>
<Grid item md={6}></Grid>
</Grid>
</div>
);
};
return withStyles(styles)(WithStyles);
};
const styles = {
bottomgap: {
marginBottom: "10px"
}
};
export default Form;
You are attempting to use a higher-order component (HOC) inside of your component. You need to use the HOC outside of the component.
const Form = ({ classes }) => { ...
export default withStyles(styles)(Form);
You are also applying the class name as a literal string className="classes.bottom-gap" rather than applying the actual class name from the classes object. It should be
className={classes.bottomgap}
import React, { useState } from "react";
import {
Grid,
FormControl,
FormControlLabel,
Switch,
TextField
} from "#material-ui/core";
import { withStyles } from "#material-ui/core/styles";
const Form = ({ classes }) => {
//Input
const [project, setProject] = useState({
id: "",
name: "",
isPublic: false
});
const handleChange = (prop) => (event) => {
setProject({ ...project, [prop]: event.target.value });
};
const handlePermisson = (prop) => (event) => {
setProject({ ...project, [prop]: event.target.checked });
console.log(project);
};
return (
<div>
<Grid container>
<Grid item md={6}>
<FormControl
className={classes.bottomgap}
fullWidth
value={project.id}
onChange={handleChange("id")}
>
<TextField
id="project_id"
label="Project id"
variant="outlined"
/>
</FormControl>
<FormControl
fullWidth
value={project.name}
onChange={handleChange("name")}
>
<TextField
id="project_name"
label="Project name"
variant="outlined"
/>
</FormControl>
<FormControl
fullWidth
value={project.id}
onChange={handlePermisson("isPublic")}
>
<FormControlLabel control={<Switch />} label="Is Public" />
</FormControl>
</Grid>
<Grid item md={6}></Grid>
</Grid>
</div>
);
};
const styles = {
bottomgap: {
marginBottom: "10px"
}
};
export default withStyles(styles)(Form);

React js material ui Grid responsive

As you can see from the image on the left I have a map with the controls, on the right I have a series of fields (last update, a table and an input field).
What I would like to do is that when it reaches a certain size (device example) the right side goes down under the map, the map then takes all the available space.
As you can see from the image when you resize a part of the table you do not see, you have to scroll.
Can you give me a hand?
In the original project I also use:
"tailwindcss": "1.2.0",
"tailwindcss-dir": "4.0.0"
Link: codesandbox
Code:
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import {
Grid,
TextField,
Paper,
Typography,
Tooltip,
Chip
} from "#material-ui/core";
import { red, teal } from "#material-ui/core/colors";
import Map from "./Map";
import ToggleButtonMap from "./ToggleButtonMap";
import DataTable from "react-data-table-component";
import "./styles.css";
const useStyles = makeStyles((theme) => ({
root: {},
paper: {
display: "flex",
border: `1px solid ${theme.palette.divider}`,
flexWrap: "wrap",
padding: 10
},
control: {}
}));
export default function App() {
const [state, setState] = React.useState({
historyParking: [
{
idPs: "7ff2-4e5d-b164-661b511e609e-1",
free: false,
latitude: 33,
longitude: 10,
timeCurrent: "23/10/2020 15:13:23"
},
{
idPs: "7ff2-4e5d-b164-661b511e609e-1",
free: true,
latitude: 33,
longitude: 10,
timeCurrent: "23/10/2020 15:13:23"
}
]
});
const { historyParking } = state;
const classes = useStyles();
const columns = [
{
name: "Name",
selector: "idPs",
cell: ({ idPs }) => (
<Tooltip title={`${idPs}`} placement="right-start" arrow>
<span>{shortCode(camPlace(idPs).idPs)}</span>
</Tooltip>
)
},
{
name: "Place",
selector: "idPs",
cell: ({ idPs }) => camPlace(idPs).place
},
{
name: "Status",
selector: "free",
cell: ({ free }) => (
<div>
<Chip
variant="outlined"
style={{
color: free ? teal["600"] : red["600"],
borderColor: free ? teal["600"] : red["600"]
}}
label={`${fixName(free?.toString())}`}
size="small"
/>
</div>
)
},
{
name: "Last update",
selector: "timeCurrent",
cell: ({ timeCurrent }) => (
<Tooltip title={`${timeCurrent}`} placement="right-start" arrow>
<span>{timeCurrent}</span>
</Tooltip>
)
}
];
const shortCode = (code, left = 10, right = 10) => {
return `${code.substring(0, left)}...${code.substring(
code.length - right,
code.length
)}`;
};
const fixName = (name) => {
return name
?.replace("_", " ")
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
};
const camPlace = (a) => {
const idPs = a.split("-");
const place = idPs.pop();
return { idPs: idPs.join("-"), place };
};
return (
<>
<Grid container spacing={2}>
<Grid item xs={8}>
<Paper elevation={1} className={classes.paper}>
<Grid container spacing={2}>
<Grid item>
<ToggleButtonMap />
</Grid>
<Grid item xs={12} sm={12} className="h-512">
<Map />
</Grid>
</Grid>
</Paper>
</Grid>
<Grid item xs={4}>
<Grid container direction="column" spacing={1}>
<Grid item>
<TextField
id="city_zone"
variant="outlined"
size="small"
></TextField>
</Grid>
<Grid item>
<Typography component="div">
Last update: 23/10/2020 16:31:35
</Typography>
</Grid>
<Grid item>
<div
style={{
border: "1px solid #dadce0",
backgroundColor: "#fff",
marginTop: 5
}}
>
<DataTable
title={"History"}
columns={columns}
data={historyParking}
highlightOnHover
defaultSortField="timeCurrent"
defaultSortAsc={false}
pagination
paginationPerPage={6}
/>
</div>
</Grid>
</Grid>
</Grid>
</Grid>
</>
);
}
This might be what you are looking for
<Grid item xs={8} sm={12}>
<Paper elevation={1} className={classes.paper}>
<Grid container spacing={2}>
<Grid item>
<ToggleButtonMap />
</Grid>
<Grid item xs={12} className="h-512">
<Map />
</Grid>
</Grid>
</Paper>
</Grid>

React JS with Material UI - When using withStyles this.props is undefined

When I run the code below I expected that styles would be injected inside props, but I always end up getting undefined props.
I am not providing any props to this component.
const styles = theme => ({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: '25ch',
},
},
});
class Editor extends React.Component {
render() {
const { classes } = this.props;
return (
<div className="editor">
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Standard" />
<Button variant="contained" color="primary">
Hello World
</Button>
</form>
</div>
);
}
}
export default withStyles(styles)(Editor);
Hi you can use makeStyles from '#material-ui/core/styles'. Please check complete example below:
import React from 'react';
import {makeStyles} from '#material-ui/core/styles';
import Grid from '#material-ui/core/Grid';
import FormLabel from '#material-ui/core/FormLabel';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import RadioGroup from '#material-ui/core/RadioGroup';
import Radio from '#material-ui/core/Radio';
import Paper from '#material-ui/core/Paper';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
height: 140,
width: 100,
},
control: {
padding: theme.spacing(2),
},
}));
export default function SpacingGrid() {
const [spacing, setSpacing] = React.useState(2);
const classes = useStyles();
const handleChange = (event) => {
setSpacing(Number(event.target.value));
};
return (
<Grid container className={classes.root} spacing={2}>
<Grid item xs={12}>
<Grid container justify="center" spacing={spacing}>
{[0, 1, 2].map((value) => (
<Grid key={value} item>
<Paper className={classes.paper}/>
</Grid>
))}
</Grid>
</Grid>
<Grid item xs={12}>
<Paper className={classes.control}>
<Grid container>
<Grid item>
<FormLabel>spacing</FormLabel>
<RadioGroup
name="spacing"
aria-label="spacing"
value={spacing.toString()}
onChange={handleChange}
row
>
{[0, 1, 2].map((value) => (
<FormControlLabel
key={value}
value={value.toString()}
control={<Radio/>}
label={value.toString()}
/>
))}
</RadioGroup>
</Grid>
</Grid>
</Paper>
</Grid>
</Grid>
);
}
Source

What is the problem of glitch when scrolling using react-window?

I want to do row virtualization when scrolling (so that data is shown when scrolling)
But when scrolling, now the terrible glitches appear
Tell me what is the problem?
project - male-wind.surge.sh
A component with a table (react-window is used there):
import React, { Component } from "react";
import { connect } from "react-redux";
import actions from "../../actions";
import PropTypes from "prop-types";
import sort from "./sort";
import { FixedSizeList } from 'react-window';
function TitleColumn(data) {
return (
<Grid item xs={1}>
<Box className="title_elem">
<h3
className="table_title-text"
onClick={sort.bind(null, `${data.title.toLowerCase()}`, data.props)}
>
{data.title}
</h3>
{data.props.fourthData.data === `${data.title.toLowerCase()}` ? (
<p>{data.props.fifthData.data}</p>
) : null}
</Box>
</Grid>
);
}
class Table extends Component {
render() {
const data = this.props.info;
const Row = ({ index, style}) => {
return (
<Grid container className="table_row">
<Grid item xs={1}>
<Box className="table_elem name_elem">{data[index].name}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem job_elem">{data[index].job}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem city_elem">{data[index].city}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem country_elem">{data[index].country}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem latitude_elem">{data[index].latitude}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem longitude_elem">{data[index].longitude}</Box>
</Grid>
<Grid item xs={1}>
<Box className="table_elem date_elem">
{`${data[index].date.toLocaleString("en", {
year: "numeric",
month: "long",
day: "numeric"
})}`}
</Box>
</Grid>
</Grid>
)
};
return (
<Grid
container
className="developer_block-time_feature time_feature_block"
>
<Grid container className="table_title">
<TitleColumn props={this.props} title="Name" />
<TitleColumn props={this.props} title="Job" />
<TitleColumn props={this.props} title="City" />
<TitleColumn props={this.props} title="Country" />
<TitleColumn props={this.props} title="Latitude" />
<TitleColumn props={this.props} title="Longitude" />
<TitleColumn props={this.props} title="Date" />
</Grid>
<FixedSizeList <---------------use react-window
height={500}
itemSize={60}
itemCount={data.length}
className="list-container"
>
{Row}
</FixedSizeList>
</Grid>
);
}
}
Table.propTypes = {
fourthData: PropTypes.object.isRequired,
fifthData: PropTypes.object.isRequired
};
const mapStateToProps = store => {
return {
firstData: store.firstData,
secondData: store.secondData,
thirdData: store.thirdData,
fourthData: store.fourthData,
fifthData: store.fifthData
};
};
const mapDispatchToProps = dispatch => {
return {
setData: data => dispatch(actions.setData(data)),
changeSearchData: searchData =>
dispatch(actions.changeSearchData(searchData)),
changeSort: sort => dispatch(actions.changeSort(sort)),
setSortTitle: sortField => dispatch(actions.setSortTitle(sortField)),
changeArrow: arrow => dispatch(actions.changeArrow(arrow))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Table);
I try to use this solution, but it does not help - https://github.com/bvaughn/react-virtualized/issues/1327
you have to apply the style passed by list for list element rendering which sets height, width and top attributes. you can do as below
const Row = ({ index, style}) => {
return (
<Grid container className="table_row" style={style}>
<Grid item xs={1}>
<Box className="table_elem name_elem">{data[index].name}</Box>
</Grid>....…..

Categories