Copied code for dialog in material-ui from docs, but isn't working, what am I doing wrong? - javascript

I copied code for material-ui dialog feature for react, but couldn't figure out why this isn't working at all. Clicking the contact button doesn't even cause it to call the handleClickOpen method.
The contact button is the one that's supposed to open the dialog box, all the dialog code is copied from the docs of material-ui so I'm not sure how this couldn't be working.
export default function Banner() {
const [open, setOpen] = React.useState(false);
function handleClickOpen() {
setOpen(true);
}
function handleClose() {
setOpen(false);
}
const classes = useStyles();
return (
<Container maxWidth="lg">
<div className={classes.root}>
<Grid container spacing={7}>
<Grid item lg={6} xs={12}>
<div className={classes.title}>
<Title content="Freightage Solutions" />
<br />
<SubTitle content="A lean, modern, and efficient shipping brokerage." />
<div className={classes.buttons}>
<Button ClassName={classes.button} content="Get Started" color='white' />
<Button ClassName={classes.button} content="Contact Us" color='blue' onClick = {handleClickOpen} />
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{"Use Google's location service?"}</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
Let Google help apps determine location. This means sending anonymous location data to
Google, even when no apps are running.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
Disagree
</Button>
<Button onClick={handleClose} color="primary" autoFocus>
Agree
</Button>
</DialogActions>
</Dialog>
</div>
</div>
</Grid>
<Grid item lg={6} xs={12}>
<img src={Image} className={classes.image} />
</Grid>
</Grid>
</div>
</Container>
);
}
EDIT: Here is the custom button component I'm using
import React from 'react';
import Typography from '#material-ui/core/Typography';
import { styled } from '#material-ui/styles';
import createBreakpoints from "#material-ui/core/styles/createBreakpoints";
import Button from "#material-ui/core/Button"
const breakpoints = createBreakpoints({});
const CustomButton = styled(Button)({
border: '2px solid #FFFFFF',
borderRadius: 80,
height: 48,
padding: '0 20px',
textTransform: 'none',
marginBottom: '20px',
marginRight: '30px',
marginLeft: '30px',
[breakpoints.up("lg")]: {
marginLeft: '0px',
},
});
const BlueButton = styled(CustomButton)({
background: '#0071F7',
color: 'white',
'&:hover': {
background: 'white',
color: '#0071F7',
},
});
const WhiteButton = styled(CustomButton)({
background: 'white',
color: '#0071F7',
'&:hover': {
background: '#0071F7',
color: 'white',
}
});
const ButtonType = styled(Typography)({
fontFamily: 'Ubuntu',
fontWeight: 450,
});
export default class Title extends React.Component {
render (){
if(this.props.color == 'white'){
return (
<WhiteButton gutterBottom>
<ButtonType>
{this.props.content}
</ButtonType>
</WhiteButton>
)
} else{
return(
<BlueButton gutterBottom>
<ButtonType>
{this.props.content}
</ButtonType>
</BlueButton>
)
}
}
}

It would be a good idea to use the onClick-prop you provided with to your CustomButton and set it on your button.
export default class Title extends React.Component {
render () {
if(this.props.color == 'white'){
return (
<WhiteButton onClick={this.props.onClick} gutterBottom>
<ButtonType>
{this.props.content}
</ButtonType>
</WhiteButton>
)
} else{
return(
<BlueButton onClick={this.props.onClick} gutterBottom>
<ButtonType>
{this.props.content}
</ButtonType>
</BlueButton>
)
}
}
}

As per the API Doc, there is no props called content for Button instead use children like,
<Button className={classes.button} children="Get Started" style={{color:'white'}} />
<Button className={classes.button} children="Contact Us" style={{color:'blue'}} onClick = {handleClickOpen} />
Update
You are using Button name to your custom component and material-ui also have the component with same name. As you are using both in same place there is a conflict and not a error from material-ui which one to use and your functionality is not working. This is probably the problem.
Try to change your custom button component name and check if it works.
Update 2
if(this.props.color == 'white'){
return (
<WhiteButton gutterBottom>
<ButtonType>
<Button onClick={this.props.onClick}>{this.props.content}</Button> //You forgot to use Button here
</ButtonType>
</WhiteButton>
)
} else{
return(
<BlueButton gutterBottom>
<ButtonType>
<Button onClick={this.props.onClick}>{this.props.content}</Button>
</ButtonType>
</BlueButton>
)
}

you should use proper material-ui Button API(https://material-ui.com/api/button/)
<Button children="Get Started" style={{color:'white'}} />
<Button children="Contact Us" style={{color:'blue'}} onClick = {handleClickOpen} />
check this: https://codesandbox.io/s/3fl8r

Related

How to reload a webpage once routed to using react-router-dom

Re-asking from a previous questions as this could be a work around.
I have a widget I'm using from a software provider (Mindbody) it needs to load some data using a <script> tag which I have in the head of my app. The page is being routed to using react-router-dom. The problem the js data only loads when you refresh the page.
What is a good method to reloading a page as soon as the page is routed to. I tried window.location.refresh(); but this loads infinite time.
import * as React from 'react';
import { Stack, Box, Typography, Modal, Backdrop } from '#mui/material';
import ButtonV2 from './ButtonV2';
import PurchaseWidget from './PurchaseWidget';
const style = {
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: 400,
bgcolor: 'background.paper',
boxShadow: 24,
borderRadius: 3,
transition: "5s ease-in-out"
};
const PurchaseLanding = () => {
const [show, setShow] = React.useState(true);
const handleClose = () => setShow(false);
return (
<div>
<Modal
open={show}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
disableAutoFocus="true"
BackdropComponent={Backdrop}
BackdropProps={{
timeout: 500,
}}>
<Box sx={style}>
<div>
{/* full width image */}
<img style={{borderRadius: "10px 10px 0 0"}} src="https://res.cloudinary.com/djjb1vyjm/image/upload/v1660541084/1_uxhi8p.png" width="100%" alt="" />
</div>
<Box p={2}>
{/* title */}
<Typography align="center" id="modal-modal-title" variant="h5" component="h2">
<span className='space-font-heavy'>Buy your [10-pack]</span>
</Typography>
{/* onboarding message */}
<Stack pb={3} alignItems="center" justifyContent="center" direction="row" spacing={2}>
<Typography px={1} align="center" id="modal-modal-description" sx={{ mt: 2 }}>
<span className='space-font-light'>Once completed download the Mindbody app to add, update, and book your workouts!</span>
</Typography>
</Stack>
{/* button group left/right */}
<Stack direction="row" justifyContent="center" alignItems="center">
<ButtonV2 />
</Stack>
</Box>
</Box>
</Modal>
</div>
);
}
export default PurchaseLanding

Cannot Link to part of page with MUI 5 Drawer

I'm simply trying to link to a specific part of my first page when the user clicks on the Shop button in the navigation Drawer but it doesn't do anything at all:
This is the code for the MUI 5 Drawer component:
<Drawer
anchor="left"
open={open}
onClose={() => setOpen(false)}
PaperProps={{
sx: {
background: "linear-gradient(to top, #9C685B44, #9C685Bff)",
},
}}
>
<IconButton onClick={() => setOpen(false)}>
<ChevronLeftIcon sx={{ color: "white" }} />
</IconButton>
<Divider />
<List>
/////////////////////////////////
<ListItem>
<Button
// Linking to Products Section
href="#products"
startIcon={<PhoneAndroidIcon />}
sx={{
color: "white",
fontFamily: "Montserrat",
}}
>
Shop
</Button>
</ListItem>
//////////////////////////////
<ListItem>
<Badge color="error" badgeContent={badgeNumber}>
<Button
startIcon={<ShoppingCartIcon />}
sx={{
color: "white",
fontFamily: "Montserrat",
}}
>
Cart
</Button>
</Badge>
</ListItem>
</List>
</Drawer>
And in that respective section, I have added an id with the value of products to the container:
<Container maxWidth="xl" id="products">
...
</Container>
Even using the anchor tag results in the same issue.
Is there anyway to fix this?
You can use scrollIntoView and History.pushState() to handle this. Remove the href from your Button component, and instead use its onClick method to call the following:
// id is your section names (e.g. 'products')
// url is optional, and if not specified, is set to the document's current URL
const onNavClick = (event, id, url) =>
{
let element = document.getElementById(id)
event.preventDefault()
element.scrollIntoView()
window.history.pushState(id, id, url)
}
There are various other options you can pass into scrollIntoView, and you can find out more about the available options by following the link above.

MUI Collapse component not allowing encapsulated element flex-grow

So I'm a newbie when it comes to React and thought to get familiar with the concepts utilizing mui. I'm creating a nav bar and one of the features is to have a search bar that is initially collapsed and expand once the search icon is pressed. This will also hide the typography element. My issue seems that no matter if I set flexgrow for both collapse or the text input that's being encapsulated the element doesn't seem to grow despite the extra space. I also observed when I set the width of the element using vw it adjusts but the right icons and search bar begin to overlap after minimizing it to a certain point. I wonder if this is a styling issue or whether if transition is incapable of doing this, if it's a styling issue how do I get the text input to expand the needed space?
Navbar.js
import React, { useState } from "react";
import {
AppBar,
Drawer,
Box,
IconButton,
List,
ListItemButton,
ListItemText,
Toolbar,
TextField,
Typography,
Collapse,
} from "#mui/material";
import MenuIcon from "#mui/icons-material/Menu";
import PersonOutlineOutlinedIcon from "#mui/icons-material/PersonOutlineOutlined";
import SearchOutlinedIcon from "#mui/icons-material/SearchOutlined";
import ShoppingBagOutlinedIcon from "#mui/icons-material/ShoppingBagOutlined";
import { createTheme } from "#mui/material";
const Navbar = () => {
const [drawer, setDrawer] = useState(false);
const [drawer2, setDrawer2] = useState(false);
const [clicked, setClicked] = useState(false);
const theme = createTheme({
typography: {
fontFamily: ["Abril Fatface", "cursive"].join(","),
},
});
return (
<AppBar position="fixed" sx={{ height: 70 }} className="navbar">
<Toolbar>
<IconButton onClick={() => setDrawer(!drawer)} className="id">
<MenuIcon fontSize="large"></MenuIcon>
</IconButton>
<Drawer open={drawer} onClose={() => setDrawer(!drawer)}>
<Box sx={{ width: 400, backgroundColor: "red" }}>
<List>
<ListItemButton>
<ListItemText primary="HI" />
</ListItemButton>
</List>
</Box>
</Drawer>
<Collapse orientation="horizontal" in={clicked} timeout={100} unmountOnExit>
<TextField sx={{ flexGrow: 2 }} />
</Collapse>
<Typography
component="a"
variant="h4"
theme={theme}
className="item"
sx={{
color: "black",
flexGrow: 2,
textAlign: "center",
display: clicked ? "none" : "block",
}}
>
APPSTUFF
</Typography>
<IconButton className="id">
<PersonOutlineOutlinedIcon fontSize="large"></PersonOutlineOutlinedIcon>
</IconButton>
<IconButton className="id" onClick={() => setClicked(!clicked)}>
<SearchOutlinedIcon fontSize="large"></SearchOutlinedIcon>
</IconButton>
<IconButton className="id" onClick={() => setDrawer2(!drawer2)}>
<ShoppingBagOutlinedIcon fontSize="large"></ShoppingBagOutlinedIcon>
</IconButton>
<Drawer
open={drawer2}
onClose={() => setDrawer2(!drawer2)}
anchor="right"
>
<Box sx={{ width: 400, backgroundColor: "red" }}>
<List>
<ListItemButton>
<ListItemText primary="HI" />
</ListItemButton>
</List>
</Box>
</Drawer>
</Toolbar>
</AppBar>
);
};
export default Navbar;
NavbarStyle.css
.id {
color: black;
margin-top: 0.5%;
display: flex;
flex-grow: 0;
}
.navbar {
width: 100vw;
box-shadow: none;
background-color: white;
}

Server Error ReferenceError: window is not defined This error happened while generating the page

I want to add Microsoft Login Button in Next Js using material Ui but
when I add package from NPM and refresh the page I got the above
error.
When I Assign ClientId="a973536f-eb3e-4fd9-9394-9f4194d69153" to Microsoft component as shown below I got the above error. How to cope with this error.
import React from "react";
import { Grid, Container, Checkbox, IconButton, FormControlLabel, TextField, Button, Link } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import Icon from "#material-ui/core/Icon";
import { loadCSS } from "fg-loadcss";
import FacebookLogin from "react-facebook-login/dist/facebook-login-render-props";
import { GoogleLogin } from "react-google-login";
import MicrosoftLogin from "react-microsoft-login";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(0),
display: "flex",
flexDirection: "column",
alignItems: "center",
height: '60vh',
},
background: {
backgroundColor: "#220E1A",
borderRadius: "5px",
color: "white",import React from "react";
import { Grid, Container, Checkbox, IconButton, FormControlLabel, TextField, Button, Link } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import Icon from "#material-ui/core/Icon";
import { loadCSS } from "fg-loadcss";
import FacebookLogin from "react-facebook-login/dist/facebook-login-render-props";
import { GoogleLogin } from "react-google-login";
import MicrosoftLogin from "react-microsoft-login";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(0),
display: "flex",
flexDirection: "column",
alignItems: "center",
height: '60vh',
},
background: {
backgroundColor: "#220E1A",
borderRadius: "5px",
color: "white",
},
form: {
width: "70%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
input1: {
background: "white",
borderRadius: "25px",
color: "white",
},
submit: {
margin: theme.spacing(1, 0, 1),
borderRadius: "25px",
},
buttonGroup: {
borderRadius: "50px",
margin: theme.spacing(2, 0, 2, 0),
},
winIcon: {
padding: '0px',
margin: '0px',
width: '10px'
}
}));
export default function SignIn() {
const classes = useStyles();
//Load Fonts awesome icons
React.useEffect(() => {
const node = loadCSS(
"https://use.fontawesome.com/releases/v5.12.0/css/all.css",
document.querySelector("#font-awesome-css")
);
return () => {
node.parentNode.removeChild(node);
};
}, []);
//google facebook,Microsoft Login response
const responseFacebook = (response) => {
console.log(response);
};
const responseGoogle = (response) => {
console.log(response);
};
const authHandler = (err, data) => {
console.log(err, data);
};
return (
<Container maxWidth="xm" className={classes.background}>
<div className={classes.paper}>
<form className={classes.form} noValidate>
<TextField
className={classes.input1}
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoFocus
variant="filled"
/>
<TextField
className={classes.input1}
variant="filled"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Grid
container
direction="column"
justify="center"
alignItems="center"
>
<Grid item >
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Stay signed in"
/>
</Grid>
<Grid item>
<Button
type="submit"
medium
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</Grid>
<Grid item>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<h3 align="center">Or Via</h3>{" "}
<FacebookLogin
appId="225241158739281"
autoLoad
callback={responseFacebook}
render={(renderProps) => (
<IconButton color="primary" onClick={renderProps.onClick}>
<Icon className="fab fa-facebook" />
</IconButton>
)}
/>
<GoogleLogin
clientId="500452257814-peb71oi9612hv04svvfpvfrtch6pc5br.apps.googleusercontent.com"
render={(renderProps) => (
<IconButton
onClick={renderProps.onClick}
>
{" "}
<Icon className="fab fa-google" color="primary" />
</IconButton>
)}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
//**Problem is here IN MicrosoftLogin when i assign Id it creates the above error.**
<MicrosoftLogin
// clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>}
/>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
},
form: {
width: "70%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
input1: {
background: "white",
borderRadius: "25px",
color: "white",
},
submit: {
margin: theme.spacing(1, 0, 1),
borderRadius: "25px",
},
buttonGroup: {
borderRadius: "50px",
margin: theme.spacing(2, 0, 2, 0),
},
winIcon: {
padding: '0px',
margin: '0px',
width: '10px'
}
}));
export default function SignIn() {
const classes = useStyles();
//Load Fonts awesome icons
React.useEffect(() => {
const node = loadCSS(
"https://use.fontawesome.com/releases/v5.12.0/css/all.css",
document.querySelector("#font-awesome-css")
);
return () => {
node.parentNode.removeChild(node);
};
}, []);
//google facebook,Microsoft Login response
const responseFacebook = (response) => {
console.log(response);
};
const responseGoogle = (response) => {
console.log(response);
};
const authHandler = (err, data) => {
console.log(err, data);
};
return (
<Container maxWidth="xm" className={classes.background}>
<div className={classes.paper}>
<form className={classes.form} noValidate>
<TextField
className={classes.input1}
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoFocus
variant="filled"
/>
<TextField
className={classes.input1}
variant="filled"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Grid
container
direction="column"
justify="center"
alignItems="center"
>
<Grid item >
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Stay signed in"
/>
</Grid>
<Grid item>
<Button
type="submit"
medium
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</Grid>
<Grid item>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<h3 align="center">Or Via</h3>{" "}
<FacebookLogin
appId="225241158739281"
autoLoad
callback={responseFacebook}
render={(renderProps) => (
<IconButton color="primary" onClick={renderProps.onClick}>
<Icon className="fab fa-facebook" />
</IconButton>
)}
/>
<GoogleLogin
clientId="500452257814-peb71oi9612hv04svvfpvfrtch6pc5br.apps.googleusercontent.com"
render={(renderProps) => (
<IconButton
onClick={renderProps.onClick}
>
{" "}
<Icon className="fab fa-google" color="primary" />
</IconButton>
)}
buttonText="Login"
onSuccess={responseGoogle}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
//**Problem is here IN MicrosoftLogin when i assign Id it creates the above error.**
<MicrosoftLogin
// clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>}
/>
</Grid>
</Grid>
</form>
</div>
</Container>
);
}
It's related to server side rendering and client side rendering.
As Next.js provides SSR, you need to consider using objects like window, localStorage and so on. While compiling client side, those objects are fine but when Nextjs compiles server side, it shows error like you shared.
It seems like GoogleLogin uses window object if you assign the client id. You need to check that first. And lemme know the result.
Hey the easy way for Material UI Components, to rendered it on Next js framework.Just use component to render it on client side only.
(If any component use Window object on server side it will show this error)
solution:
import NoSsr from '#material-ui/core/NoSsr';
<NoSsr>
<MicrosoftLogin
clientId="a973536f-eb3e-4fd9-9394-9f4194d69153"
authCallback={authHandler}
redirectUri="https://localhost:3000/"
className={classes.winIcon}
children={
<IconButton>
<Icon className="fab fa-windows" color="primary" />
</IconButton>
}
/>
</NoSsr>

Full width material-ui Button within a Badge?

I have a Button inside a Grid and was using fullWidth to expand it to fill the container.
This worked fine, until I wrapped it in a Badge. Now the fullWidth property is ignored and the button is default width.
Worked fine:
<Button variant={"outlined"} color={"secondary"} fullWidth>
Todo
</Button>
Now not working:
<Badge badgeContent={4} color={"secondary"}>
<Button variant={"outlined"} color={"secondary"} fullWidth>
Todo
</Button>
</Badge>
How can I get the button to expand to fill its parent?
import React, {Component} from 'react';
import Grid from "#material-ui/core/Grid/Grid";
import Button from "#material-ui/core/Button/Button";
import Badge from "#material-ui/core/Badge/Badge";
export default class App extends Component {
render() {
return (
<Grid container style={{margin: 10}}>
<Grid item xs={2}>
<Badge badgeContent={4} color={"secondary"}>
<Button variant={"outlined"} color={"secondary"} fullWidth>
Todo badge
</Button>
</Badge>
<Button variant={"outlined"} color={"secondary"} fullWidth>
Todo no badge
</Button>
</Grid>
<Grid item xs={10}>
</Grid>
</Grid>
);
}
};
you have to apply fullWidth property to badge
<Badge badgeContent={4} color={"secondary"} fullWidth>
<Button variant={"outlined"} color={"secondary"}>
Todo
</Button>
</Badge>
Just add this property: fullWidth={true}
import { Button } from "#mui/material";
<Button
variant="contained"
fullWidth={true}
type="submit"
>
Click me
</Button>
docs:
https://mui.com/api/button/
I could come up with a solution using width CSS property:
here is my answer:
const styles = theme => ({
margin: {
margin: theme.spacing.unit * 2,
width: '100%'
}
});
function SimpleBadge(props) {
const { classes } = props;
return (
<Grid container>
<Grid item xs={11}>
<Badge color="primary" badgeContent={4} className={classes.margin} >
<Button variant="contained" fullWidth>Button</Button>
</Badge>
</Grid>
</Grid>
);
}
please find that I have used width: '100%' in badge styles.
here is a working example: https://codesandbox.io/s/wqm9kmxmql
hope this will help you.
One easy way is to use the sx prop on the Badge to set the width to '100%'.
<Badge sx={{ width: '100%' }} variant="dot" color="primary" badgeContent={1}>
<Button fullWidth variant="contained" color="neutral">
Button
</Button>
</Badge>
And make sure you have fullWidth set on the Button

Categories