3

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>
Joy
  • 105
  • 1
  • 2
  • 10

2 Answers2

4

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>
TomS
  • 635
  • 5
  • 9
  • Thank you!!! Exactly what I needed, without a button click or the onChange Event. – Joy Feb 23 '22 at 13:23
0

inside the form put a button and trigger the getValues() method. like below

<button
    type="button"
    onClick={() => {
      const values = getValues(); // { page_title: "someValue", test1: "test1-input", ... }
      console.log({values});
    }}
  >
    Get Values
  </button>

Have a look at this basic example from the docs link too

Wahab Shah
  • 2,066
  • 1
  • 14
  • 19
  • Thank you for the answer! Can it be done without any button click? Like as the user fills the form, the preview shows the values entered. – Joy Feb 23 '22 at 13:03
  • yeah onChange method of input element. Create a onChangeHandler and maybe use a useState to update the value as entered. – Wahab Shah Feb 23 '22 at 13:10