DEV Community

Cover image for How to get user input value from an input tag in Reactjs?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get user input value from an input tag in Reactjs?

Originally posted here!

To get input value from an input tag in Reactjs, you can use the target.value property of the Event which is passed by the onChange handler whenever the user types on the input tag.

For example first let's make an input tag,

export default InputTag(){
    return (
        <input type="text" />
    );
}
Enter fullscreen mode Exit fullscreen mode

After that, we can attach an onChange handler to it so that whenever the user types on the input field it should invoke the function provided in the onChange handler.

NOTE: onChange attribute - The handler function attached to this attribute will be invoked every time whenever the user types something into the input field.

it can be done like this,

export default InputTag(){
    // onChange Handler function
    const getInputValue = ()=>{
        // do cool stuff here!
    };

    return (
        // Add onChange handler with function to execute
        <input type="text" onChange={getInputValue} />
    );
}
Enter fullscreen mode Exit fullscreen mode

Now we have a working handler that will be invoked whenever when the user enters something into the input field.

Still, we haven't added the logic to get the user input value. Let's add that now!

Every time the user enters something into the input field a Synthetic Event is passed as a parameter to the onChange handler function. Thus the user input value is present in the event.target.value property.

So in the onChange handler function let's write a parameter called event like this,

export default InputTag(){
    // onChange Handler function
    // with event parameter
    const getInputValue = (event)=>{
        // show the user input value to console
        const userValue = event.target.value;

        console.log(userValue);
    };

    return (
        // Add onChnage handler with function to execute
        <input type="text" onChange={getInputValue} />
    );
}
Enter fullscreen mode Exit fullscreen mode

Now type something into the input field and you can see that value by opening the console.

Yay! That's it! πŸ”₯πŸ˜ƒ. We have successfully retrieved the user input value in Reactjs.

You can also store the userValue into a react state to use it to process information or for sending the value to a server etc.

See the above code in action in Codesandbox.

Feel free to share if you found this useful πŸ˜ƒ.


Top comments (0)