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>
Related
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.
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
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>....…..
I use a button from another component to access this Favorites component, but when I press the button, it doesn't load anything and the page goes blank. Now if I press the button twice, it shows me the information.
const Favorites = (props) => {
const [products, setProducts] = useState([]);
useEffect(() =>{
let productsArray = []
firebase.database().ref().child('favorites').orderByKey()
.once('value', snap => {
snap.forEach(child => {
if(child.val().user_id === firebase.auth().currentUser.uid){
firebase.database().ref('products/' + child.val().product_id)
.once('value')
.then(snapshot =>{
const favorite = {
id: snapshot.key,
name: snapshot.val().name,
category: snapshot.val().category,
description: snapshot.val().description,
image: snapshot.val().image,
price: snapshot.val().price,
stock: snapshot.val().stock,
};
productsArray.push(favorite);
});
}
});
setProducts(productsArray);
});
},[]);
return (
<Fragment>
<ul>
{ products && products.map((item, index) => {
return(
<Grid container justify="center" alignItems="center" key={index}>
<div className={classes.root}>
<Paper className={classes.paper}>
<Grid container spacing={2}>
<Grid item>
<ButtonBase className={classes.image}>
<img className={classes.img} alt="complex" src={item.image} />
</ButtonBase>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={2}>
<Grid item xs>
<Typography gutterBottom variant="subtitle1">
{item.name}
</Typography>
<Typography variant="body2" gutterBottom>
{"Categoria: " + item.category}
</Typography>
<Typography variant="body2" color="textSecondary">
{item.description}
</Typography>
</Grid>
<Grid item>
<Button
onClick={(event) => removeFavorite(event, index)}>
<HighlightOff/> Eliminar de Favoritos
</Button>
</Grid>
</Grid>
<Grid item>
<Typography variant="subtitle1">{"Bs " + item.price + "/ Kg"}</Typography>
</Grid>
</Grid>
</Grid>
</Paper>
</div>
</Grid>
);
})
}
</ul>
</Fragment>
);
}
export default Favorites;
I think I am doing something wrong with the useEffect() when I perform the query and store it with the setProducts() fix. I don't know what's happening, why does it go blank and then rerun the Favorites component if it shows? I appreciate your help.
In the App component I have the Shopping Cart Sharp button, which redirects to "/ shoppingcart", which is the component where I have the problem.
const MyLink = React.forwardRef((props, ref) => <RouterLink innerRef={ref}
{...props} />);
function App() {
const [user, setUser] = useState(null);
const onLogout = () => {
setUser(null);
};
return (
<Router>
<CssBaseLine/>
<Header user={user}>
{user && <Button to="/shoppingcart" component={MyLink}
color="inherit"><ShoppingCartSharp /></Button>}
</Header>
<Routes/>
</Router>
);
}
export default App;
I'm trying to achieve a specific layout using the Material UI Grid Component, but I just cannot for the life of me get it right.
I have a Dialog where I want the Layout to end up like this:
Where the blue box contains some information about a project, the green box will contain some sort of media and the yellow box will contain a descriptive text.
But currently, with this code, it ends up like this:
<Grid xl={12}>
<Grid spacing={0} xs={2}>
<Grid container direction="column">
<Grid item xs={1}>
{ this.getGridItems("Platforms", data["platforms"].split(','), true) }
</Grid>
<Grid item xs={1}>
{ this.getGridItems("Engines", data["engines"].split(','), true) }
</Grid>
<Grid item xs={1}>
{ this.getGridItems("Frameworks", data["frameworks"].split(','), true) }
</Grid>
<Grid item xs={1}>
{ this.getGridItems("Languages", data["languages"].split(',')) }
</Grid>
<Grid item xs={1}>
{ this.getGridItems("Roles", data["roles"].split(',')) }
</Grid>
</Grid>
</Grid>
<Grid spacing={0} xl={10}>
<Grid container>
<Grid item xl={9}>
<h1>Image Goes Here</h1>
</Grid>
<Grid item xl={3}>
<h1>Description</h1>
{ data["description"] }
</Grid>
</Grid>
</Grid>
</Grid>
I cannot quite figure out where I went wrong as I can't wrap my head around how the Grid layout works. Please help?
If it's necessary, here is the code for getGridItems():
getGridItems = (header, data, chips) => {
let list = [];
let fontSize = 11;
list.push(
<h5>{ header }</h5>
);
if(data.length > 0 && data[0] !== '') {
if(chips !== undefined && true) {
data.forEach(value => {
let chipData = ChipConstants[value];
list.push(
<Grid item xs>
<Chip
style={{ fontSize: fontSize}}
avatar={
<Avatar
style={{ width: 24, height: 24 }}
alt={chipData["avatar"]["alt"]}
src={require("../img/avatars/"+chipData["avatar"]["img"])}
/>}
label={chipData["avatar"]["alt"]}
className={styles.chip}
/>
</Grid>
);
});
} else {
data.forEach(value => {
list.push(
<Grid item xs style={{ fontSize: fontSize}}>
{ value }
</Grid>
);
});
}
} else {
list.push(
<Grid item xs style={{ fontSize: fontSize}}>
None
</Grid>
);
}
return list;
};
I'm not really seeing how your current code relates to what you want, so instead of trying to correct your current code, I'll just provide a starting point that provides the basic structure of what you want.
If you have specific questions about how the Grid in my code works, I'll elaborate as needed.
index.js
import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "#material-ui/core/CssBaseline";
import Button from "#material-ui/core/Button";
import MyDialog from "./MyDialog";
class App extends React.Component {
state = {
open: false
};
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
return (
<>
<CssBaseline />
<Button variant="contained" onClick={this.handleClickOpen}>
Open Dialog
</Button>
<MyDialog open={this.state.open} handleClose={this.handleClose} />
</>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
MyDialog.js
import React from "react";
import Grid from "#material-ui/core/Grid";
import Dialog from "#material-ui/core/Dialog";
import IconButton from "#material-ui/core/IconButton";
import CloseIcon from "#material-ui/icons/Close";
import { withStyles } from "#material-ui/core/styles";
const styles = {
root: {
height: "100%"
},
project: {
backgroundColor: "lightblue",
height: "100%"
},
right: {
height: "100%"
},
media: {
backgroundColor: "lightgreen",
height: "70%"
},
desc: {
backgroundColor: "yellow",
height: "30%"
}
};
const MyDialog = props => {
return (
<Dialog fullScreen open={props.open} onClose={props.handleClose}>
<Grid container className={props.classes.root}>
<Grid item xs={3} className={props.classes.project}>
<IconButton
color="inherit"
onClick={props.handleClose}
aria-label="Close"
>
<CloseIcon />
</IconButton>
Project
</Grid>
<Grid item xs={9}>
<Grid container direction="column" className={props.classes.right}>
<Grid item className={props.classes.media}>
Media
</Grid>
<Grid item className={props.classes.desc}>
Description
</Grid>
</Grid>
</Grid>
</Grid>
</Dialog>
);
};
export default withStyles(styles)(MyDialog);
Here it is in a CodeSandbox you can experiment with: