0

In the following code I am setting up a ref on the <input/> element which is used during the <form> element's onSubmit handler.

For some reason I am getting the following error when submitting the form:

TypeError: Cannot read property 'value' of undefined

How can I prevent this error?

import React from "react";

class AddItemForm extends React.Component {

  nameRef = React.createRef();

  createItem = event => {

    event.preventDefault();

    const item = {
      name: this.nameRef.value.value,      
    };  
  }

  render() {
    return (
      <form className="item-edit" onSubmit={this.createItem}>
        <input name="name" ref={this.nameRef} type="text" placeholder="Name" />        
        <button type="submit">+ Add Item</button>
      </form>
    );
  }
}

export default AddItemForm;
0

1 Answer 1

3

You need to replace the first value with current seeing that the ref object provides access to the underlying DOM element via that field.

The following should resolve your problem:

createItem = event => {
    event.preventDefault();
    const item = {
       name: this.nameRef.current.value,      // Replace value with current 
    };
    console.log(item);      
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.