-2

Could I please ask you to write some easy example of using react ref callback? I want to see, how can I take an input value after I push a button using ref callback, because I don't get it and I can't find a full example.

For example I have some form with input surname, and button submit. This button call function that console log input surname value. How can I do it?

Jarrod L
  • 285
  • 5
  • 16
FKa
  • 47
  • 1
  • 7

1 Answers1

1

Here you go.

class App extends Component {
  constructor(props) {
    super(props);
  }

  submit = () => {
    // get ref value
    const surname = this.surname.getValue();
    console.log('surname===>',surname)
  }

  render() {
    return (
      <div>
        {/* surname field */}
        <input 
          type='text' 
          ref=((ref) => this.surname = ref)
          placeholder='enter your surname'/>
        {/* submit button */} 
        <input type="submit" value="Submit" onClick={this.submit}>
      </div>
    )
  }
}
Shubham
  • 1,163
  • 2
  • 12
  • 36
  • Insteade of it won't work (arrow function, and "Cannot read property 'surname' of undefined") this example is really clar for me. Thank you very much – FKa Nov 20 '17 at 10:42
  • OK, it should be "this.surname.value", no "this.surname.getValue()". And, of corse, you have to bind function. I wanted show full code, but unfortunately stackOverflow "no longer accepting answers from this account". But it work – FKa Nov 20 '17 at 11:05
  • @FKa you don't need to bind the function If you use the function in the similar way that I used. – Shubham Nov 20 '17 at 11:07
  • Yep, I know, you don't need bind function if you use arrow function; but if you want arrow function in react, you need stage-1 Babel preset. Thank you for your help and time :-) – FKa Nov 20 '17 at 11:12