Diego Cardona
Diego Cardona

Reputation: 385

Why: Cannot read property 'email' of undefined? React-dom

I need to use my state in another component, i sent it with props like that.

Okay, this is my ./HandleForm container.

import React, { PureComponent } from "react";

import NotLoggedRegisterForm from "./NotLoggedRegisterForm";

export default class HandleForm extends PureComponent {
  state = {
    data: {
      email: "",
      password: "",
      confirmPassword: ""
    }
  };

  handleChange = e => {
    this.setState({ ...this.state.data, [e.target.name]: e.target.value });
  };

  render() {
    return (
      <div>
        <NotLoggedRegisterForm data={this.state.data} />
      </div>
    );
  }
}

this is a part of the component than receive the props.

const { data } = props.data;

<Input
        prefix={<Icon type="mail" style={{ color: "rgba(0,0,0,.25)" }} />}
        type="email"
        placeholder="Email"
        name="email"
        onChange={props.handleChange}
        value={data.email}
      />

And i receive that error code:

TypeError
Cannot read property 'email' of undefined
NotLoggedRegisterForm
/src/pages/logged/not/registerForm/NotLoggedRegisterForm.js:38:24
  35 |       placeholder="Email"
  36 |       name="email"
  37 |       onChange={props.handleChange}
> 38 |       value={data.email}
     |                  ^
  39 |     />
  40 |   )}
  41 | </FormItem>

Upvotes: 0

Views: 2051

Answers (2)

Julian
Julian

Reputation: 1622

in your code

const { data } = props.data is wrong.

Because props contains data, while props.data doesn't contain data so you may change like this.

const data = props.data;
// or you may use "const {data} = props;"

<Input
        prefix={<Icon type="mail" style={{ color: "rgba(0,0,0,.25)" }} />}
        type="email"
        placeholder="Email"
        name="email"
        onChange={props.handleChange}
        value={data.email}
      />

Upvotes: 0

Lu Tran
Lu Tran

Reputation: 401

change

const { data } = props.data;

into

const { data } = props;

Upvotes: 1

Related Questions