breakpoints not working in MUI v5 and react project - javascript

I'm trying to use breakpoints for responsive design in my page, but it dosent really seem to work. Whenever i apply any breakpoint, the whole page goes blank.
Here's my code:-
Styles.js
import { makeStyles } from "#mui/styles";
const useStyles = makeStyles((theme) => ({
title: {
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
}));
export default useStyles;
Header.jsx
import React from 'react';
import { Autocomplete } from '#react-google-maps/api';
import { AppBar, Toolbar, Typography, InputBase, Box } from '#mui/material';
import SearchIcon from '#mui/icons-material/Search';
import useStyles from './styles';
const Header = () => {
const classes = useStyles();
return (
<>
<AppBar position='static'>
<Toolbar className={classes.toolbar}>
<Typography variant='h5' className={classes.title}>
Travel Advisor
</Typography>
{/* Box acts as Div */}
<Box display='flex'>
<Typography variant='h6' className={classes.title}>
Explore new places
</Typography>
{/* <Autocomplete> */}
<div className={classes.search}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<InputBase placeholder='Search...' classes={{ root: classes.inputRoot, input: classes.inputInput }} />
</div>
{/* </Autocomplete> */}
</Box>
</Toolbar>
</AppBar>
</>
)
}
export default Header;
Before applying breakpoints :-
Before breakpoint
After applying breakpoints :-
After breakpoint

Make sure that you created breakpoints correctly.
https://mui.com/material-ui/customization/breakpoints/
And check if you have wrapped your app in ThemeProvider.
And I want to note that #mui/styles is deprecated. Perhaps this problem may be related to this.
https://mui.com/system/styles/basics/
⚠️ #mui/styles is the legacy styling solution for MUI. It depends on JSS as a styling solution, which is not used in the #mui/material anymore, deprecated in v5. If you don't want to have both Emotion & JSS in your bundle, please refer to the #mui/system documentation which is the recommended alternative.
⚠️ #mui/styles is not compatible with React.StrictMode or React 18.
Dont use it on newly created app.

Related

Uncaught TypeError: Cannot read properties of undefined (reading '8')

This is my first time posting and I am a junior Frontend developer so please go easy on me.
This has me very confused and I've looked, tested and for some reason the Inputlabel from Material UI (ver. 5) is not working on this side of the website I am developing. I used inputlabel and date picker on the home page and they work with no problems. But suddenly trying to make a user profile form... Well, it's starting to give me trouble. Literally copying what is in the documentation and still get this issue.
When I click on the Input everythig on the page disappears. Opening the Chrome Inspector gives me the error that's in the title. And I am truly clueless. Posting my code to see if someone cand lend me a bit of help here. Thank you in advance.
import React from 'react';
import { TextField } from '#mui/material';
import { Grid } from '#mui/material';
import { Box } from '#mui/system';
import { Container } from '#mui/material';
import InputLabel from '#mui/material/InputLabel';
import MenuItem from '#mui/material/MenuItem';
import FormControl from '#mui/material/FormControl';
import Select from '#mui/material/Select';
import { DatePicker } from "#mui/lab";
import { LocalizationProvider } from "#mui/lab";
import AdapterDateFns from '#mui/lab/AdapterDateFns';
//import '../User/components/styles/UserStyles.scss';
const UserProfileTxt = () => {
//DOB picker
const [dob, setDob] = React.useState(new Date())
//Nationality Picker
const [nationality, setNationality] = React.useState('');
const handleChange = (event) => {
setNationality(event.target.value);
};
return (
<Container>
<Grid container>
<Grid sx={{ flexDirection: 'column', display: 'flex' }}>
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}} variant='outlined' label='Nombre' />
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}} variant='outlined' label='Apellido' />
<TextField sx={{mt:'0.5rem', mb:'0.5rem'}}variant='outlined' label='E-mail' />
<Box sx={{ minWidth: 120, mt:'0.5rem', mb:'1rem' }}>
<FormControl fullWidth>
<InputLabel id="NationalityUSERHIKLUB">Nacionalidad</InputLabel>
<Select
labelId="Nacionalidad"
id="Naccionalidad"
value={nationality}
label="Nationalidad"
onChange={handleChange}
>
<MenuItem value={1}>Ten</MenuItem>
</Select>
</FormControl>
</Box>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Seleccióna fecha de Nacimiento"
value={dob}
onChange={(newValue) => {
setDob(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</Grid>
<Grid>
</Grid>
</Grid>
</Container>
);
};
export default UserProfileTxt;
Okay. I solved my own question.
This is probably a bug, but I didn't add this to the original question because I seriously didn't think it was going to be related. Despite that, I am going to share it in case someone is having issues as well.
So, this form I am doing is inside a <Tabs/> component, which I costumized using <ThemeProvider/> and <CreateTheme/>. Started basically breaking my code down seeing where the error could stem from. Finally, I noticed that it could be the <ThemeProvider/> on the tabs. And sure enough, once I removed both <ThemeProvider/> and <CreateTheme/> The date picker and dropdown menu were working fine.
Sorry I didn't address it before but I seriously did not think it was going to be related to the issue at hand
So, long story short:
DO NOT USE THEMEPROVIDER WHEN USING TABS ON MUI VER 5. USE STYLED COMPONENTS INSTEAD AND GET THE SAME RESULT WITH A LOT LESS ISSUES. I suppose there is some sort of conflict with that and the tabs component.
Thanks to anyone who answered.

Problems with React Router/Hoook

Update (new changes):
So now I pretty much converted my code to a functional component however it is as if nothing is being returned from the API, or perhaps I am not "mounting" correctly? I get the error " TypeError: Cannot read property 'map' of undefined" meaning nothing is being returned but I'm not sure why. Help?
Old post (I had previously tried to use a hook in a a class component):
I'm pretty brand new to react and recently I have been getting this error from when trying to navigate to a page on click of a card media (using material ui). So I pretty much follow the instruction to push to history the route to the page I want to navigate to via a function and call that function when I click the media card. Below is my code and the error I get. Do you have any idea why I might be having an issue with this?
My updated code
import Card from '#material-ui/core/Card';
import CardMedia from '#material-ui/core/CardMedia';
import Grid from '#material-ui/core/Grid';
import Container from '#material-ui/core/Container';
import {getItems} from "../Network/network_utility";
import {useHistory} from "react-router-dom";
import {makeStyles} from '#material-ui/core/styles';
import React, {useState, useEffect} from "react";
const useStyles = makeStyles(theme => ({
icon: {
marginRight: theme.spacing(2),
},
heroContent: {
padding: theme.spacing(8, 0, 6),
},
cardGrid: {
paddingTop: theme.spacing(6),
paddingBottom: theme.spacing(3),
position: "fixed"
}
}));
export default function Items() {
let history = useHistory();
const classes = useStyles();
const useFeaturedItems = () => {
const [featured_items, setFeaturedItems] = useState([]);
useEffect(() => {
getItems(1).then(response => setFeaturedItems(response["data"]))}, []);
return featured_items;
};
return (
<div>
<Container className={classes.cardGrid} maxWidth="lg">
<Grid container spacing={6}>
{useFeaturedItems().map((card, index) => (
<Grid item key={index} xs={16} sm={4} md={2}>
<Card raised={false} style={{height: "30vh", width: "20vh"}}>
<CardMedia
component="img"
src={card["thumbnail"]}
style={{height: "25vh", width: "20vh"}}
onClick={history.push("/item")}
>
</CardMedia>
<div style={{paddingLeft: "10px", paddingTop: "10px"}}>
<text style={{
whiteSpace: "nowrap",
overflow: "hidden",
display: "block",
textOverflow: "ellipsis"
}}>
{card["title"]}
</text>
</div>
</Card>
</Grid>
))}
</Grid>
</Container>
</div>
);
}
As I can see you are using hook inside a class component. It is not possibile
how use hook
You can’t use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component. In the longer term, we expect Hooks to be the primary way people write React components.
In class component you need to use the HOC withRouter. After that you can access the history through props with this.props.history

Warning: Functions are not valid as a React child.This may happen if you return a Component instead of <Component /> from render

I get the above error when I try to display {props.child}.The page remains blank.The detailed warning is
index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
in div (at CustomLayout.js:28)
in main (created by Basic)
in Basic (created by Context.Consumer)
in Content (at CustomLayout.js:22)
in section (created by BasicLayout)
in BasicLayout (created by Context.Consumer)
in Layout (at CustomLayout.js:8)
in CustomLayout (at App.js:10)
in div (at App.js:9)
in App (at src/index.js:7)
Below are the project files. Article.js is a component and ArticleListView and CustomLayout are containers to it. I am trying to access the child elements in CustomLayout.js by {props.children}
App.js
import React from 'react';
import './App.css';
import 'antd/dist/antd.css';
import CustomLayout from './containers/CustomLayout'
import ArticleListView from './containers/ArticleListView';
function App() {
return (
<div className="App">
<CustomLayout>
{ArticleListView}
</CustomLayout>
</div>
);
}
export default App
ArticleListView.js
import React from 'react'
import Article from '../components/Article'
class ArticleListView extends React.Component{
render(){
return(
<Article/>
);
}
}
export default ArticleListView
Article.js
import React from 'react'
import { List, Avatar, Icon } from 'antd';
const listData = [];
for (let i = 0; i < 23; i++) {
listData.push({
href: 'http://ant.design',
title: `ant design part ${i}`,
avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
description:
'Ant Design, a design language for background applications, is refined by Ant UED Team.',
content:
'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.',
});
}
const IconText = ({ type, text }) => (
<span>
<Icon type={type} style={{ marginRight: 8 }} />
{text}
</span>
);
function Article(props){
return(
<List
itemLayout="vertical"
size="large"
pagination={{
onChange: page => {
console.log(page);
},
pageSize: 3,
}}
dataSource={listData}
footer={
<div>
<b>ant design</b> footer part
</div>
}
renderItem={item => (
<List.Item
key={item.title}
actions={[
<IconText type="star-o" text="156" key="list-vertical-star-o" />,
<IconText type="like-o" text="156" key="list-vertical-like-o" />,
<IconText type="message" text="2" key="list-vertical-message" />,
]}
extra={
<img
width={272}
alt="logo"
src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png"
/>
}
>
<List.Item.Meta
avatar={<Avatar src={item.avatar} />}
title={<a href={item.href}>{item.title}</a>}
description={item.description}
/>
{item.content}
</List.Item>
)}
/>
);
}
export default <Article/>
CustomLayout.js
import React from 'react'
import { Layout, Menu, Breadcrumb } from 'antd';
const { Header, Content, Footer } = Layout;
function CustomLayout(props){
return(
<Layout className="layout">
<Header>
<div className="logo" />
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={['2']}
style={{ lineHeight: '64px' }}
>
<Menu.Item key="1">nav 1</Menu.Item>
<Menu.Item key="2">nav 2</Menu.Item>
<Menu.Item key="3">nav 3</Menu.Item>
</Menu>
</Header>
<Content style={{ padding: '0 50px' }}>
<Breadcrumb style={{ margin: '16px 0' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>List</Breadcrumb.Item>
<Breadcrumb.Item>App</Breadcrumb.Item>
</Breadcrumb>
<div style={{ background: '#fff', padding: 24, minHeight: 280 }}>{props.children}</div>
</Content>
<Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
</Layout>
);
}
export default CustomLayout
If you are using any javascript expression then only use curly braces like - {a+b}.
but form html tags or react component you need to import as per react standard.
Use like this
<CustomLayout>
<ArticleListView />
</CustomLayout>
and change your export default <Article/> to export default Article
It should be <ArticleListView/>, not {ArticleListView}
Try
<CustomLayout>
<ArticleListView />
</CustomLayout>
rather than
<CustomLayout>
{ArticleListView}
</CustomLayout>
in javascript we work like isConditionTrue ? screenOne :screenTwo
but in typescript we have to change isConditionTrue ? :

How to set a HTML element ID on a material-ui component?

I have a website built with Gatsby.js using the Material-UI.
Specific problem is this: I want to use the Google Tag Manager "Element Visibility" triggers. If some HTML element becomes visible, GTM should fire some GA tag.
Question is this: how can I specify the HTML ID for a material-ui component for GTM (or anything else) to find it?
First example:
// ...react imports omitted...
import makeStyles from '#material-ui/core/styles/makeStyles';
import Box from '#material-ui/core/Box';
import Grid from '#material-ui/core/Grid';
import CloseIcon from '#material-ui/icons/Close';
import Link from '~components/Link';
import ButtonSubmit from '~components/form-buttons/ButtonSubmit';
import Container from '~components/Container';
// ... all other imports are in-house code
const useStyles = makeStyles(theme => ({ /* ...styles... */}));
const GuestUserSoftSaleSecondPopup = ({ which, ...rest }) => {
const classes = useStyles();
// ...setup code omitted...
return (
<Box bgcolor="#474d5c" width="100%" py={4} className={classes.banner}>
<Container>
<Grid container direction="row" justify="space-between" alignItems="center" spacing={2}>
<Grid item xs={12} sm={1} md={3} lg={4}>
<CloseIcon onClick={handleClose} size="large" className={classes.closeIcon} />
</Grid>
<Grid item xs={12} sm={7} md={5} lg={4}>
<Link to="/subscribe" variant="h5" className={classes.linkStyle}>
Become a member for full access
</Link>
</Grid>
<Grid item xs={12} sm={4} className={classes.buttonPosition}>
<Link to="/subscribe" underline="none" className={classes.linkStyle}>
<ButtonSubmit type="button" fullWidth={false}>
See my option
</ButtonSubmit>
</Link>
</Grid>
</Grid>
</Container>
</Box>
);
};
// ...proptypes and `export` clause
Second example:
// ...react imports omitted...
import makeStyles from '#material-ui/core/styles/makeStyles';
import MuiDialog from '#material-ui/core/Dialog';
const useStyles = makeStyles(() => ({ /* ...styles... */ }));
const Dialog = ({ children, background, backdrop, isOpen, ...rest }) => {
const classes = useStyles({ background });
return (
<MuiDialog
open={isOpen}
maxWidth="sm"
fullWidth
disableBackdropClick
disableEscapeKeyDown
BackdropProps={{
className: backdrop ? classes.backdropBM : classes.backdrop
}}
PaperProps={{
className: classes.paper
}}
scroll="body"
{...rest}
>
{children}
</MuiDialog>
);
};
If you look at the API documentation for almost any of the Material-UI components, you will find at the end of the "Props" section a statement like the following example from Dialog:
Any other props supplied will be provided to the root element (Modal).
This means that any props not explicitly recognized by this component will be passed along eventually to whatever HTML element is the outermost element rendered. So for most Material-UI components, in order to add an id property, you just specify it.
My example below (a modification of the Simple Dialog demo) includes three different ids: one on the Dialog element which will be placed on the outermost div of the Modal, one specified via the PaperProps which will go on the main Paper div of the visible content of the dialog, and one on the Box wrapped around the dialog content.
import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Avatar from "#material-ui/core/Avatar";
import List from "#material-ui/core/List";
import ListItem from "#material-ui/core/ListItem";
import ListItemAvatar from "#material-ui/core/ListItemAvatar";
import ListItemText from "#material-ui/core/ListItemText";
import DialogTitle from "#material-ui/core/DialogTitle";
import Dialog from "#material-ui/core/Dialog";
import PersonIcon from "#material-ui/icons/Person";
import Typography from "#material-ui/core/Typography";
import { blue } from "#material-ui/core/colors";
import Box from "#material-ui/core/Box";
const emails = ["username#gmail.com", "user02#gmail.com"];
const useStyles = makeStyles({
avatar: {
backgroundColor: blue[100],
color: blue[600]
}
});
function SimpleDialog(props) {
const classes = useStyles();
const { onClose, selectedValue, open } = props;
const handleClose = () => {
onClose(selectedValue);
};
const handleListItemClick = value => {
onClose(value);
};
return (
<Dialog
onClose={handleClose}
aria-labelledby="simple-dialog-title"
open={open}
PaperProps={{ id: "MyDialogPaperID" }}
id="ThisIDWillBeOnTheModal"
>
<DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
<Box id="MyBoxID">
<List>
{emails.map(email => (
<ListItem
button
onClick={() => handleListItemClick(email)}
key={email}
>
<ListItemAvatar>
<Avatar className={classes.avatar}>
<PersonIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary={email} />
</ListItem>
))}
</List>
</Box>
</Dialog>
);
}
SimpleDialog.propTypes = {
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
selectedValue: PropTypes.string.isRequired
};
export default function SimpleDialogDemo() {
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(emails[1]);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = value => {
setOpen(false);
setSelectedValue(value);
};
return (
<div>
<Typography variant="subtitle1">Selected: {selectedValue}</Typography>
<br />
<Button variant="outlined" color="primary" onClick={handleClickOpen}>
Open simple dialog
</Button>
<SimpleDialog
selectedValue={selectedValue}
open={open}
onClose={handleClose}
/>
</div>
);
}
Material UI components don't let you set an id for them since the implementation inside should be a black box and may contain multiple html element. See if you can wrap the element in a div and put the id on that instead.
Another option would be to add a class (via the classes prop) to the element instead but I'm not sure if Google Tag Manager can use those instead of ids.

How to set the style a react.js component when creating it?

How to set the style a react.js component when creating it?
Below is some of my code (partially inherited from a stronger developer and then simplified for brevity).
I want to re-use my LogComponent to print several pages of a Log. However, in some cases I want to force a particular width on the returned List, rather than allowing it to flex as it sees fit.
I would prefer to not define a separate LogComponentFixed or to have an if (...) {return (...)} else {return(...)} in my LogComponent.
I have in mind to do something in Log.js like:
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_2} />
And to then, in LogComponent do something like:
<List style={style}> ... </List>
I also tried using something like
<List className={list_1}> ... </List>
But none of the things I've tried works...
Log.js
import React from 'react'
import Typography from '#material-ui/core/Typography'
import { withStyles } from '#material-ui/core/styles'
import LogComponent from './LogComponent'
const styles = theme => ({
title: {
padding: theme.spacing.unit*1.5,
},
list_1: {
},
list_2: {
width: "300px"
},
listContainer: {
flexGrow: 1,
minHeight: 0,
overflow: 'auto'
},
})
const Log = ({classes, log}) => {
const page_1 = log[0];
const page_2 = log[1];
return (
<div>
<Typography className={classes.title} color="textSecondary" key={1}>
Example Log
</Typography>
<div className={classes.listContainer} key={2}>
<LogComponent heading={'Page 1'} lines={page_1} />
<LogComponent heading={'Page 2'} lines={page_2} />
</div>
</div>
export default withStyles(styles)(Log)
LogComponent.js
import React from 'react'
import Typography from '#material-ui/core/Typography'
import { withStyles } from '#material-ui/core/styles'
import { List, ListItem, ListItemText } from '#material-ui/core';
const styles = theme => ({
title: {
padding: theme.spacing.unit*1.5,
},
}
const LogComponent = ({classes, list_class, heading, lines}) => {
return (
<div className={classes.root}>
<Typography className={classes.title} color="textSecondary" key={1}>
{heading}
</Typography>
<div>
<List dense>
{[...lines[0]].map(e =>
<ListItem><ListItemText primary={e} /></ListItem>
)}
</List>
</div>
</div>
)
}
export default withStyles(styles)(LogComponent)
Here you are sending the styles as a prop to LogComponent, that's why it will not be applied as styles to that component you have created. The style attribute is for HTML tags and in material-ui, you can pass styles to a wrapper component also.
In your case you can get the styles inside your LogComponent as below:
Send styles as a prop as you mentioned in the question
<LogComponent heading={"Page 1"}, lines={page_1}, style={styles.list_1} />
Now, you can access it from props,
// right below get the style
const LogComponent = ({classes, list_class, heading, lines, style}) => {
return (
<div className={classes.root} style={style}> // Look style attribute added, style(value) is from props
<Typography className={classes.title} color="textSecondary" key={1}>
{heading}
</Typography>
<div>
<List dense>
{[...lines[0]].map(e =>
<ListItem><ListItemText primary={e} /></ListItem>
)}
</List>
</div>
</div>
)
}

Categories