Accessing the value of input in Reactjs


How can we access the value of input React ? We have pretty programmatic approach to access the DOM and its props.

For this we have to create and assign the ref to the input and in a event handler we can access it by using the current object. Don’t know how to create a ref ? Here is the Guide

Button and Event Handler

Now we want a button and handler function, which is a simple arrow function. As follows

import React, { Component } from 'react'

 class InputRef extends Component {
     constructor(props) {
         super(props)
         this.input_ref=React.createRef()
     }
 
     clickHandler=()=>{
         alert(this.input_ref.current.value)
     }
    render() {
        return (
            <div>
                <input type="text" ref={this.input_ref} />
                <button onClick={this.clickHandler}>Click me </button>
            </div>
        )
    }
}

export default InputRef

In the event handler we make use of ref object’s current to access the DOM and then call the props value to access the input value.

That’s all you need to know, may be you want to look for the following posts too

Event handling in class component in Reactjs - How to handle event in a class component in Reactjs UI. Here is the right approach for bigdata apps

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.