Nedjim DN
Nedjim DN

Reputation: 543

I can't read attribut 'ref' of dom element in react

I can't read attribute ref after the form validation. The result is undefined and I don't understand why.

import React from 'react';
import {Link} from 'react-router-dom';

export default class Home extends React.Component {.

handleSubmit(e){
    e.preventDefault();

    console.log(e.name.value);
}

render() {
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <input type='text' ref={ (input) => this.name = input} />
                <input type='text' ref={ (input) => this.topic = input} />
                <input type='submit'/>
            </form>
        </div>
    )
} 

}

Upvotes: 1

Views: 177

Answers (3)

skylize
skylize

Reputation: 1421

The e variable is holding an event. You are looking for e.target to get the element the event was fired on.

console.log(e.target.name.value);

Upvotes: 0

Adil
Adil

Reputation: 629

You may need to log this.name.value instead of this console.log(e.name.value);

You also need to include this

constructor(props){
    super(props)
    this.handleSubmit = this.handleSubmit.bind(this)
}

Upvotes: 0

Mario F
Mario F

Reputation: 47279

you are storing it in the component itself, the value should be available under

console.log(this.name)

e is the event that gets triggered when you click on the input. In your case, you are using an arrow function, so this in the context of the callback is the Home component.

EDIT:

You also need to bind handleSubmit so that it has access to the right this. Add this to the Home component:

constructor () {
  super()
  this.handleSubmit = this.handleSubmit.bind(this)
}

Upvotes: 2

Related Questions