Categories
React Answers

How to get the value of an input from the input’s ref in a React component?

Spread the love

Sometimes, we want to get the value of an input from the input’s ref in a React component.

In this article, we’ll look at how to get the value of an input from the input’s ref in a React component.

How to get the value of an input from the input’s ref in a React component?

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const cityInput = useRef();

  const onSubmit = (e) => {
    e.preventDefault();
    console.log(cityInput.current.value);
  };

  return (
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Enter City Name" ref={cityInput} />
      <button>Go!</button>
    </form>
  );
}

We create a cityInput ref with the useRef hook.

Then we define the onSubmit function that gets the input’s value by using cityInput.current.value.

We call e.preventDefault to stop the default server side submission behavior.

Next, we set the ref prop of the input to cityInput so that cityInput.current is set to the input element.

Finally, we set the onSubmit prop to onSubmit to run it when we click Go.

Conclusion

To get the value of an input from the input’s ref in a React component, we can use the value attribute.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *