Search code examples
reactjsreact-hook-formuse-form

React useForm get value from TextBox


I am using React useForm hook to submit data from my form. The requirement is the user should see the sample data in a preview div before he submits. How can i get the value from input text boxes and display it in a div next to the input. In the documentation there is getValue method can that be used?

<form>
<div class="mb-6">
            <label  class="block mb-2">Enter Title: </label>
            <input  type="text" id="page_text" class="text-white" placeholder="Enter Title" {...register('page_Title',{ required: "Enter Your Title", maxLength: {value:255,message:"Cannot Exceed more 255 Characters" } })}/>
</div>
</form>
<div className= "text-white text-center rounded-xl shadow-xl">
            <h1>Preview</h1>
            <h3>{getValues("page_Title")}</h3>
</div>

Solution

  • I've created a sandbox here: https://codesandbox.io/s/angry-wave-nef2jo

    Basically the issue is getValues doesn't automatically update when you enter text (onChange). You need to use the watch method as described in the documentation here: https://react-hook-form.com/api/useform/watch

    For example:

    const pageTitle = watch("page_Title", false);
    

    Then:

    <h3>{pageTitle}</h3>