Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material-UI Modal TypeError: Cannot read property 'hasOwnProperty' of undefined

Any time I add a modal to one of my classes I get this error.

TypeError: Cannot read property 'hasOwnProperty' of undefined

Here's a basic example where I'm just trying to always show a basic modal. Any ideas? I've tried various examples that should work, but nothing I have tried prevents the error. Seems if I add Modal then it just errors.

Edit: Figured out the issue. The modal requires a single root level child you need to embed all your content in.

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { Schema, Field } from "v4f";
import Modal from '@material-ui/core/Modal';

const styles = theme => ({
    '@global': {
        body: {
            backgroundColor: theme.palette.common.white,
        },
    },
    paper: {
        marginTop: theme.spacing(8),
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
    },
    avatar: {
        margin: theme.spacing(1),
        backgroundColor: theme.palette.secondary.main,
    },
    form: {
        width: '100%', // Fix IE 11 issue.
        marginTop: theme.spacing(1),
    },
    submit: {
        margin: theme.spacing(3, 0, 2),
    },
});

const initState = {
    email: "",
    password: "",
    errors: {}
};

const SignInValidator = Schema(
    {
        email: Field()
            .string()
            .email({ message: "Not an e-mail address" })
            .required({ message: "E-mail is required" }),
        password: Field()
            .string()
            .required({ message: "Password is required" })
    },
    { verbose: true, async: true  }
    // We set the options on creation all call to Schema Product will be verbose and async
);

class SignIn extends React.Component
{
    constructor(props) {
        super(props);
        this.state = { ...initState };
    }

    //Handle Submit & Handle Change
    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    }

    handleDirty = (e) => {
        const { name, value } = e.target;
        const isValid = SignInValidator[name].validate(value, {
            verbose: true,
            values: this.state
        });

        if (isValid !== true) {
            this.setState({
                errors: { ...this.state.errors, [name]: isValid }
            });
        }
        else {
            this.setState({
                errors: { ...this.state.errors, [name]: undefined }
            });
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        SignInValidator.validate(this.state)
            .then(data => {
                this.login();
            })
            .catch(errors => {
                this.setState({ errors });
            });
    }

    login = (e) => {


        var email = encodeURI(this.state.email);
        var password = encodeURI(this.state.password);
        fetch(`/login/login?Username=${email}&Password=${password}`)
            .then(data => {
                console.log(data);
                alert("Login Success!");
                //Navigate to the dashboard
                this.setState(initState);
            })
            .catch(e => {
                alert("Login Failed");
                console.error(e);
            });
    };

    render()
    {
        const { classes } = this.props; 

        return (
            <Container component="main" maxWidth="xs">
                <CssBaseline />
                <div className={classes.paper}>
                    <Avatar className={classes.avatar}>
                        <LockOutlinedIcon />
                    </Avatar>
                    <Typography component="h1" variant="h5">
                        Sign in
                    </Typography>
                    <form className={classes.form}>
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            id="email"
                            label="Email Address"
                            name="email"
                            autoComplete="email"
                            onChange={this.handleChange}
                            onBlur={this.handleDirty}
                            error={this.state.errors.email !== undefined}
                            helperText={this.state.errors.email}
                            value={ this.state.email }
                        />
                        <TextField
                            variant="outlined"
                            margin="normal"
                            required
                            fullWidth
                            name="password"
                            label="Password"
                            type="password"
                            id="password"
                            onChange={this.handleChange}
                            onBlur={this.handleDirty}
                            error={this.state.errors.password !== undefined}
                            helperText={this.state.errors.password}
                            value={this.state.password}
                            autoComplete="current-password"
                        />
                        <FormControlLabel
                            control={<Checkbox value="remember" color="primary" />}
                            label="Remember me"
                        />
                        <Button
                            type="submit"
                            fullWidth
                            variant="contained"
                            color="primary"
                            className={classes.submit}
                            onClick={this.handleSubmit}
                        >
                            Sign In
                    </Button>
                        <Grid container>
                            <Grid item xs>
                                <Link to='/' variant="body2">
                                    Forgot password?
                            </Link>
                            </Grid>
                            <Grid item>
                                <Link to='/sign-up' variant="body2">
                                    {"Don't have an account? Sign Up"}
                                </Link>
                            </Grid>
                        </Grid>
                    </form>
                    <Modal open={true}>
                        Hello
                    </Modal>
                </div>
            </Container>
        );
    }
}

export default connect()(withStyles(styles)(SignIn));
like image 332
Chase R Lewis Avatar asked Jun 16 '19 20:06

Chase R Lewis


1 Answers

Explanation

The reason for MUI Modal component having the error

TypeError: Cannot read property 'hasOwnProperty' of undefined

Is that you didn't give a JSX component as a child.


Solution

Change from this

<Modal open={true}>
  Hello
</Modal>

to

<Modal open={true}>
  <div>  
    Hello
  </div>
</Modal>

More

If you search the source of Material-UI project by the keyword hasOwnProperty. or following the error callback stack

You would find something in

  • packages\material-ui\src\Modal\Modal.js
function getHasTransition(props) {
  return props.children ? props.children.props.hasOwnProperty('in') : false;
}

The error means the props.children.props is undefined, which gave the debug thought.

like image 64
keikai Avatar answered Nov 02 '22 10:11

keikai