1

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

}

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Nedjim DN
  • 543
  • 2
  • 6
  • 12

3 Answers3

2

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)
}
Mario F
  • 45,569
  • 6
  • 37
  • 38
  • Thank's for your answer Mario. I tried, but i have this error : "Cannot read property 'name' of undefined" – Nedjim DN Oct 10 '17 at 13:59
  • @NedjimDN you are right, your `handleSubmit` method does not have access to `this` as it is not bound to the component. I updated my answer with that. – Mario F Oct 10 '17 at 14:01
0

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)
}
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Adil
  • 240
  • 1
  • 6
  • 19
  • Thank's for your answer Adil. I tried, but i have this error : "Cannot read property 'name' of undefined" – Nedjim DN Oct 10 '17 at 13:54
0

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);
skylize
  • 1,401
  • 1
  • 9
  • 21