Search code examples
reactjsinputref

react easy example of using ref callback


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?


Solution

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