question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using ternary operator causes the fields to get incorrect defaultValue

See original GitHub issue

Hey, First off, thanks for open sourcing this library, I really appreciate it.

I encountered this issue that I’m not sure if it should be solved by the library, or if it can just be documented.

Codesandbox link (Required) https://codesandbox.io/s/loving-dew-7i24k

To Reproduce

  1. Toggle the switch
  2. Get an error

In the sandbox, you will see that I have a ternary operator that switches between 2 input fields (using controllers). The first input field expects an array, while the other expects an object. An error is thrown when you toggle between the 2 fields because React doesn’t seem to rerender with the correct defaultValue.

I managed to solve it by either:

  1. Giving each of the controllers a key prop (Uncomment them and refresh the sandbox to fix it)
  2. Using the && operator instead of ternary. This causes the controllers to unmount completely instead of rerendering.

I think you can solve #1135 the same way.

Again, I’m not sure if you think the responsibility is on react-hook-form. If not, thanks again for writing this library 😃

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
wenchongleecommented, Mar 18, 2020

I think it’s fine, but maybe adding an example would help?

React Hook Form doesn’t control your entire form and inputs, which is the reason why React wouldn’t recognise the actual input that has been exchanged or swopped. An example of this happening is when you use a ternary operator to conditionally switch between input fields. As a solution, you can resolve this problem by giving a unique key prop to your input. You can also read more about the key props from this article written by Kent C. Dodds.

Here’s a trimmed down example of my codesandbox, you could edit it to your liking and add it if you want.

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const defaultValues = {
    checked: false,
    input1: "input1",
    input2: "input2",
    input3: "input3",
    input4: "input4"
  };

  const { watch, register } = useForm({ defaultValues });
  const watchChecked = watch("checked");

  return (
    <div className="App">
      <input ref={register} name="checked" type="checkbox" />

      Without Keys, the default value will not change:
      {watchChecked ? (
        <input ref={register} name="input1" type="text" />
      ) : (
        <input ref={register} name="input2" type="text" />
      )}
  
      With Keys, the default value changes correctly:
      {watchChecked ? (
        <input ref={register} name="input3" type="text" key="key1" />
      ) : (
        <input ref={register} name="input4" type="text" key="key2" />
      )}
    </div>
  );
}

Cheers!

1reaction
bluebill1049commented, Mar 18, 2020

React Hook Form doesn’t control your entire form and inputs, which is the reason why React wouldn’t recognise the actual input that has been exchanged or swopped. As a solution, you can resolve this problem by giving a unique key prop to your input. You can also read more about the key props from this article written by Kent C. Dodds.

let me know if you think it make sense and feel free to adjust and add your words too. thanks

Read more comments on GitHub >

github_iconTop Results From Across the Web

3 Ways to Set Default Value in JavaScript | SamanthaMing.com
Let's break down the 3 different ways to set Default Values using logical operator, ternary, and if/else...
Read more >
why isn't the useWatch defaultValue not being overwritten?
I set the defaultValue to be true because leaving out the default value causes the const 'areThereUndefinedFields' to always be undefined. When ...
Read more >
Java Ternary Operator - Jenkov.com
The Java ternary operator works like a simplified if-statement which returns one of two possible values, depending on a given condition.
Read more >
Be careful when using || to set default values in JavaScript
First of all, it isn't obvious why the OR operator would be used to assign default values. It takes time for this hack...
Read more >
Nullish coalescing operator (??) - JavaScript - MDN Web Docs
The latter returns the right-hand side operand if the left operand is any falsy value, not only null or undefined . In other...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found