Dushyant Joshi
Dushyant Joshi

Reputation: 3702

ReactJS Ref: undefined error getting input element value

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;

Upvotes: 0

Views: 312

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

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);      
}

Upvotes: 3

Related Questions