Giter VIP home page Giter VIP logo

input's Introduction

npm downloads npm npm Discord

Get started | API | Form Builder | FAQs | Examples

Features

Install

npm install react-hook-form

Quickstart

import { useForm } from 'react-hook-form';

function App() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('firstName')} />
      <input {...register('lastName', { required: true })} />
      {errors.lastName && <p>Last name is required.</p>}
      <input {...register('age', { pattern: /\d+/ })} />
      {errors.age && <p>Please enter number for age.</p>}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors!

Past sponsors

Backers

Thanks go to all our backers! [Become a backer].

Contributors

Thanks go to these wonderful people! [Become a contributor].

input's People

Contributors

bluebill1049 avatar gprost avatar iamchanii avatar jeromedeleon avatar joelsaupe avatar ptunay avatar riccardocampitelli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

input's Issues

Docs - Show example with a WrappedSelect (for lack of a better term)

When I do my Select's, I like to make them into a single component (ie: <CountrySelect />) and then hand that off to RHFInput's as property.

It took me way longer than it should've to realize I needed to also pass down props from RHFInput in order for the wrapped select to work with RHFInput.

Here's a codesandbox that shows what I'm talking about: https://codesandbox.io/s/react-hook-form-rhfinput-qifbu

Not an issue with the code at all, but it just might be helpful to include something in the docs about how this use case works as I can imagine it's a fairly common pattern to keep the finished Select somewhere else and then just basically decorate it with RHFInput.

Amazing library in general so far by the way!

React Semantic UI modal with React Hook Form default values disappear

Hi,

I'm trying to create an edit user modal that gets default values of the user details from outside of the component.
The modal is written using React-Semantic-UI and triggered by "edit button". The issue is that when I exit and re-enter to the modal the default values of the form are disappear

To Reproduce

  1. Go to this sandbox
  2. Click on Edit User
  3. Exit from modal by ESC or clicking outside the modal
  4. Enter again
  5. see the Full-Name field disappear

Codesandbox link
https://codesandbox.io/s/react-semantic-ui-react-form-hook-issue-ckyt8?fontsize=14&hidenavigation=1&theme=dark

I think the issue is that the input tag is recreated every time I enter the modal again but the form reference still to the old one.

Do you have any idea how can I solve this issue?

Thanks a lot!

Mount issue on RHFInput

Hello developers, am facing this issue. I am new to this repo.
I like to share the code without the UI library. Just an input is enough to replicate the issue. Once the component is re-rendered and then we try to update the input, we are getting a warning, which is ugly. Can anyone please help me with this.

Code snippet
<RHFInput
as={ }
defaultValue={getValues().email}
rules={
{
required: 'Email is required',
pattern : {
value: /^\w+([.-]?\w+)@\w+([.-]?\w+)(.\w{2,3})+$/,
message: 'Bad email'
}
}
}
name='email'
placeholder='Enter Email'
register={register}
setValue={setValue}
/>

Error on change after re-render,
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in Unknown (at LoginComponent.js:70)
in div (created by FormGroup)
in FormGroup (at LoginComponent.js:68)
in form (created by Form)
in Form (at LoginComponent.js:67)

RHFInput + AntD TimePicker isn't working after 1.1.0

Describe the bug
RHFInput + AntD TimePicker is not working on react-hook-form-input^1.1.0.

To Reproduce
Try to change TimePicker value on each codesandbox.

Codesandbox link

Expected behavior
RHFInput + AntD TimePicker should be working even latest(>1.0.14)

Screenshots
2019-12-13 10-11-21 2019-12-13 10_11_39

2019-12-13 10-05-21 2019-12-13 10_06_16

Desktop (please complete the following information):

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Tell me if is there a point what I missed! and thank you to your works.

RHFInput 'onBlur' mode deselects selected option when using React-Select

Describe the question?
First off, great work on this library and React-Hook-Form! I wanted to see if I am using this prop,
mode='onBlur' correctly in React-Hook-Form-Input.

Here is my code:

<RHFInput
  as={<Select />}
  options={options}
  name={name}
  register={register}
  setValue={setValue}
  rules={{required: isRequired }}
  mode='onBlur'
/>

When I use the 'onBlur' mode, after selecting an item in the dropdown, and then go to another input, the item in the dropdown gets deselected.
I am using the latest version of all libraries.
I have provided an example on codesandbox.

Codesandbox link
https://codesandbox.io/s/friendly-cdn-4xgjm?fontsize=14&hidenavigation=1&theme=dark

RHFInput + Semantic UI Select / Checkbox

Hello, first of all thanks for your effort creating this library.

Today I have been trying to integrate RHF with components from Semantic UI react library. RHFInput works fine with Form.Input (basic text field), but it fails when I try to wrap Form.Select (https://react.semantic-ui.com/addons/select/) or Form.Checkbox (https://react.semantic-ui.com/modules/checkbox/) with it. I think the reason for this is that Form.Select is not implemented with traditional <select> html element, but rather with some <div> magic and Form.Checkbox also generates some strange "hidden" <input type="checkbox"> element. I believe Semantic UI is fairly popular and used library, so I think it might be worthy to look into this, thank you! Here is the simplified code I am using, nothing is sent when the form is submitted:

<Form onSubmit={handleSubmit(onSubmit)}>
  <RHFInput
    name="color"
    as={
      <Form.Select
        label="Pick a color"
        options={colors}
        required
      />
    }
    register={register}
    setValue={setValue}
  />
  <RHFInput
    name="tos"
    as={<Form.Checkbox label="Accept TOS" />}
    type="checkbox"
    register={register}
    setValue={setValue}
  />
  <Form.Button fluid>Submit</Form.Button>
</Form>

EDIT:

The checkbox generates following error: _options$0$ref.attributes is undefined and also warning Warning: Failed prop type: Invalid prop valuesupplied toCheckbox`.

And the select generates no error, but the value after submitting is always undefined.

setValue and register props are not optional when inside FormContext

Hey there,

I am implementing RHFInput in a typescript project.

I'm not sure if i am making a mistake in my code somewhere but I am trying to use RHFInput like this:

image

but I get an error telling me that they are both required.

Am i using this wrong? if not can i submit a PR?

P.S. Love your library, great work 👍.

Material UI multiple checkboxes not working properly

Describe the bug
This is related to react-hook-form/react-hook-form#476, but with Material UI added to the equation.

I have a form for multiple choice of different themes. Users can choose 1 to 3 themes. I am using RHFInput to make things easier.

However, after submitting, data is always an array of booleans.

              {AvailableThemes.map((theme, i) => (
                <FormControlLabel
                  key={theme}
                  value={theme}
                  control={
                    <RHFInput
                      as={<Checkbox />}
                      name={`themes[${i}]`}
                      type="checkbox"
                      value={theme}
                      register={register}
                      setValue={setValue}
                    />
                  }
                  label={theme}
                  className={cl.twoColumns}
                />
              ))}

To Reproduce
Steps to reproduce the behavior:

  1. Go to the sandbox bellow
  2. Check some options
  3. Submit the form
  4. See the console for the output data

Codesandbox link
https://codesandbox.io/s/material-ui-multiple-checkboxes-m6ns1

Expected behavior
The values in the array themes should be the values of the selected checkboxes, not booleans.

Desktop (please complete the following information):

  • OS: Linux
  • Browser: Firefox
  • Version: 70.0.1

Checkbox validation is not working as expected

Describe the bug
We have a form with checkbox. This checkbox has required: true validation. If checkbox is unchecked, formState.isValid should be false, but if RHFInput is used with custom checkbox, formState.isValid is true

Codesandbox link
If react-hook-form-input is used: https://codesandbox.io/s/upbeat-satoshi-2324v
Without react-hook-form input: https://codesandbox.io/s/intelligent-morse-2hgmf

Expected behavior
Submit button should be disabled if checkbox is not checked. We can see this behaviour in example without react-hook-form-input, but not in the rhfinput-powered

Question: Proper way of using RHFInput in MaterialUI custom component?

Proper way of using RHFInput in MaterialUI custom component?

I created a component wich is a wrapper of Material UI Select (not react-select). I want to know the proper way of integrating with RHF and RHFInput. I want to know if there is a better aproach, or if there´s something that I made here that is unnecesary.

If you submit without selecting an option yup validation should trigger error message in component. But it doesn't clean up if you change the option after that without submitting again.

Here is the code sandbox:

https://codesandbox.io/s/react-hook-form-mui-simple-select-0cl76?fontsize=14&hidenavigation=1&theme=dark

Cursor AutoFocus to the end on editing text

Describe the bug
The cursor to add / edit the text is automatically shifting to the end on any operation performed

To Reproduce
Steps to reproduce the behavior:

  1. Go to the First Name field in the CodeSandBox link
  2. Type in any text
  3. Delete any text in the middle
  4. See error

Codesandbox link
https://codesandbox.io/s/react-native-hooks-form-testing-723e0

Expected behavior
The cursor should remain in the same position

Screenshots
No Screenshots

Desktop (please complete the following information):

  • Any Browser
  • Latest Version

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

I already upload and get the list of product successful but Update product show for me an error. I do not know how to update my image and data on Firebase in Reactjs.

This is my code in ProductForm.js

import React, { useState, useEffect } from 'react';
import Gongcha from '../asses/gongcha.jpg'

const ProductForm = (props) => {
  const initialFieldValues = {
    image: '',
    name: '',
    category: '',
    price: ''
  };

  var [values, setValues] = useState(initialFieldValues);
  var [imageFile, setImageAsFile] = useState();

  useEffect(() => {
    if (props.currentId == '') setValues({ ...initialFieldValues });
    else
      setValues({
        ...props.productObjects[props.currentId],
      });
  }, [props.currentId, props.productObjects]);

  const handleInputChange = (e) => {
    var { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  };

  const handleFormSubmit = (e) => {
    e.preventDefault();
    props.addOrEdit(values, imageFile);
  };
  const handleImageAsFile = (e) => { 
    console.log("file image",e);
    const image = e.target.files[0]
    setImageAsFile(imageFile => (image))
}

  return (
    <form autoComplete="off" onSubmit={handleFormSubmit}>
      <div className="form-group input-group">
        <div className="input-group-prepend">
          <div className="input-group-text">
            <i className="fas fa-image"></i>
          </div>
        </div>
        <input
          className="form-control"
          type="file"
          name="image"
          placeholder="Image"
          value={values.image}
          onChange={handleImageAsFile}
        />
      </div>
      <div className="form-row">
        <div className="form-group input-group col-md-6">
          <div className="input-group-prepend">
            <div className="input-group-text">
              <i className="fas fa-mug-hot"></i>
            </div>
          </div>

          <input
            className="form-control"
            name="name"
            placeholder="Name"
            value={values.name}
            onChange={handleInputChange}
          />
        </div>
        <div className="form-group input-group col-md-6">
          <div className="input-group-prepend">
            <div className="input-group-text">
              <i className="fas fa-list-alt"></i>
            </div>
          </div>
          <input
            className="form-control"
            name="category"
            placeholder="Category"
            value={values.category}
            onChange={handleInputChange}
          />
        </div>
      </div>
      <div className="form-group input-group">
        <div className="input-group-prepend">
          <div className="input-group-text">
            <i className="fas fa-money-check-alt"></i>
          </div>
        </div>
        <input
          className="form-control"
          name="price"
          placeholder="Price"
          value={values.price}
          onChange={handleInputChange}
        />
      </div>
      <div className="form-group">
        <input
          type="submit"
          value={props.currentId == '' ? 'Save' : 'Update'}
          className="btn btn-primary btn-block"
        />
      </div>
    </form>
  );
};

export default ProductForm;

And this is the table, which the place I showed all list of product and also Action (Edit and Delete)

import React, { useState, useEffect } from 'react';
import { Card, Button, Imgage } from 'react-bootstrap'
import ProductForm from './ProductForm';
import { DB, Storage } from '../firebase';    

const Products = () => {
  var [currentId, setCurrentId] = useState('');
  var [productObjects, setProductObjects] = useState({});
  const [ImageAsUrl, setImageAsUrl] = useState()


  useEffect(() => {
    DB.ref().child('products').on('value', (snapshot) => {
      if (snapshot.val() != null) {
        setProductObjects({
          ...snapshot.val(),
        });
      }
    });
  }, []);

  const addOrEdit = (obj, image_url) => {

    let upload = Storage.ref().child(`product-img/${image_url.name}`).put(image_url)
    upload.on('state_changed',
      (snapShot) => {

        console.log(snapShot)
      }, (err) => {

        console.log(err)
      }, () => {

        Storage.ref('product-img').child(image_url.name).getDownloadURL()
          .then(fireBaseUrl => {

            DB.ref().child('products').push({ name: obj.name, image: fireBaseUrl, category: obj.category, price: obj.price }, (err) => {

              if (err) console.log(err);
              else setCurrentId('');
            })

          })
      })

    console.log("log imgage link", ImageAsUrl);
  };

  const onDelete = (id) => {
    if (window.confirm('Are you sure to delete this record?')) {
      DB.ref().child(`products/${id}`).remove((err) => {
        if (err) console.log(err);
        else setCurrentId('');
      });
    }
  };

  return (
    <>
      <div className="jumbotron jumbotron-fluid">
        <div className="container">
          <h1 className="display-4 text-center">Products Manager</h1>
        </div>
      </div>
      <div className="row">
        <div className="col-md-5">
          <ProductForm {...{ currentId, productObjects, addOrEdit }} />
        </div>
        <div className="col-md-7">
          <table className="table table-borderless table-stripped">
            <thead className="thead-light">
              <tr>
                <th>Image</th>
                <th>Name</th>
                <th>Category</th>
                <th>Price</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {Object.keys(productObjects).map((key) => (
                <tr key={key}>
                  <td>{productObjects[key].image}</td>
                  <td>{productObjects[key].name}</td>
                  <td>{productObjects[key].category}</td>
                  <td>{productObjects[key].price}</td>
                  <td className="bg-light">
                    <a
                      type="button"
                      className="btn text-primary"
                      onClick={() => {
                        setCurrentId(key);
                      }}
                    >
                      <i className="fas fa-pencil-alt"></i>
                    </a>
                    <a
                      type="button"
                      className="btn text-danger"
                      onClick={() => {
                        onDelete(key);
                      }}
                    >
                      <i className="far fa-trash-alt"></i>
                    </a>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

export default Products;

This is an Error show for me when I clicked Update icon:

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

Can anyone help me with this problem? I really do not know how to fix it. Please? Your help is my pleasure

This is my version

"firebase": "^7.17.2",
"react": "^16.13.1",
"react-bootstrap": "^1.3.0",

Using RFHInput with MaterialUI TextField : `[object HTMLInputElement]` when empty

Describe the bug
When writing in TextField MaterialUI component and deleting all characters, it fills the TextField with [object HTMLInputElement]

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s
  2. Write in 'MUI TextField'
  3. Delete all chars
  4. See error

Codesandbox link
https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s

Screenshots
ErrorRHFInput

Desktop (please complete the following information):

  • OS: [Windows]
  • Browser [Chrome]
  • Version [79.0.3945.79]

Checkbox and Switch's value is not going as `false`.

CodeSandbox Link: https://codesandbox.io/s/keen-shirley-zqh30?fontsize=14&hidenavigation=1&theme=dark

When we click on submit: it gives the following output:

{}

How can we set false value for Checkbox and Switch by default ?

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";
import { RHFInput } from "react-hook-form-input";
import { TextField, Checkbox, Button, Switch } from "@material-ui/core";

import useForm from "react-hook-form";

function App(props: RouteComponentProps) {
  const methods = useForm();

  const [data, setData] = React.useState(null);
  const { handleSubmit, register, setValue, reset, getValues } = methods;

  const onSubmit = (data: any) => setData(data);

  console.log(getValues());

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <RHFInput
        as={<Checkbox />}
        name="Checkbox"
        type="checkbox"
        value="test"
        defaultValue="false"
        register={register}
        setValue={setValue}
      />

      <RHFInput
        as={<TextField />}
        name="TextField"
        register={register}
        setValue={setValue}
      />

      <RHFInput
        as={<Switch value="checkedA" />}
        type="checkbox"
        name="switch"
        register={register}
        setValue={setValue}
      />

      {data && (
        <div style={{ textAlign: "left", color: "red" }}>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}

      <button>Submit</button>
    </form>
  );
}



const rootElement = document.getElementById("root");
render(<App />, rootElement);

export 'useFormContext' was not found in 'react-hook-form'

Receiving the following error when importing from react-hook-form-input/dist/index.es.js. I'm using import { FormContext, useForm } from 'react-hook-form/dist/react-hook-form.es' in my application.

ERROR in ./node_modules/react-hook-form-input/dist/index.es.js 95:16-30
"export 'useFormContext' was not found in 'react-hook-form'

If I manually change line 2 of node_modules/react-hook-form-input/dist/index.es.js to import { useFormContext } from 'react-hook-form/dist/react-hook-form.es';, it works fine.

I'm using webpack and typescript with ts-loader.
My tsconfig.json file:

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "lib": ["es6", "dom"],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "jsx": "react",
    "baseUrl": ".",
    "paths": {
      "@ui/*": ["app/javascript/packs/ui/*"],
      "*": ["node_modules/*", "app/javascript/*"]
    }
  },
  "exclude": [
    "**/*.spec.ts",
    "node_modules",
    "vendor",
    "public"
  ],
  "compileOnSave": false
}

Warning: A component is changing an uncontrolled input of type text to be controlled.

Describe the bug
Trying to change MUI Textfield on demo page, results a warning as follow.

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components
    in input (created by ForwardRef(InputBase))
    in div (created by ForwardRef(InputBase))
    in ForwardRef(InputBase) (created by WithStyles(ForwardRef(InputBase)))
    in WithStyles(ForwardRef(InputBase)) (created by ForwardRef(Input))
    in ForwardRef(Input) (created by WithStyles(ForwardRef(Input)))
    in WithStyles(ForwardRef(Input)) (created by ForwardRef(TextField))
    in div (created by ForwardRef(FormControl))
    in ForwardRef(FormControl) (created by WithStyles(ForwardRef(FormControl)))
    in WithStyles(ForwardRef(FormControl)) (created by ForwardRef(TextField))
    in ForwardRef(TextField) (created by WithStyles(ForwardRef(TextField)))
    in WithStyles(ForwardRef(TextField)) (at src/index.js:91)
    in RHFInput (at src/index.js:90)
    in section (at src/index.js:88)
    in div (at src/index.js:47)
    in form (at src/index.js:43)
    in ThemeProvider (at src/index.js:42)
    in App (at src/index.js:166)

To Reproduce
Steps to reproduce the behavior:

  1. Go to demo page, results a warning as follow.
  2. Open CodeSandbox Browser's Console
  3. Click on 'MUI TextField'
  4. Type anything
  5. See the error

Codesandbox link
https://codesandbox.io/s/react-hook-form-hookforminput-rzu9s

Expected behavior
No error at all

Screenshots
image

Desktop (please complete the following information):

  • OS: macOS 10.15.2
  • Browser: Chrome
  • Version: 78.0.3904.108

Usage with Baseweb

We are using baseweb as our go-to component-library at work. It's a library baked by Uber and under active development and growing.

I'd like to have more examples added to react-hook-form (or react-hook-form-input) on how these two libraries can work together. In general they work pretty well together out of the box, but as soon as you have more advanced stuff (dynamic and nested forms) it's getting quite complex. (take a look at the <Select/> component, which takes an object as it's value instead of a simple string).

Maybe someone of the core react-hook-form members can take a look at baseweb and create some arbitrary examples on how it can work with react-hook-form? I can also setup a PR.

Why always get a strange number when using the V4 version in ReactNative

Describe the question?
Only one number can be retrieved using the V4 version in ReactNative
To Reproduce

const { handleSubmit, errors, control} = useForm(); 
<Controller
            as={<Input />}
            control={control}
            name="name"
            placeholder="username"
/>
<Button
            onPress={handleSubmit(data => {
              console.log(data);
            })}>
            login
</Button>

Screenshots
image
image
Additional context
Add any other context about the problem here.

RHF Input with React-Select Libary

Hey,

when working with the RHF Input Libary and Select, the option I select is not being selected. And does not show up at the submition.

"react": "^16.12.0",
"react-hook-form": "^3.28.12",
"react-hook-form-input": "^1.1.3",

<RHFInput as={<Select width='100%' placeholder="Wunschhändler" options={sales} />} setValue={setValue} name={"whish_market"} id={"whish_market"} register={register}/>

I tried it exactly like the quick start example.

Using react-number-format floatValue

Describe the question?
Can we actually use react-number-format floatValue as the value of RHF field? The reason is because it will be very useful for validation

At the moment I can only get RHF working with formattedValue of RNF.

To Reproduce
Steps to reproduce the behavior:

  1. Implement react-number-format on top of RHF
  2. Type some numbers
  3. See RHF actually gets RNF formattedValue instead of floatValue

Codesandbox link
https://codesandbox.io/s/boring-johnson-crxsz?fontsize=14&hidenavigation=1&theme=dark

Screenshots
https://imgur.com/alUU1yH

Additional context
By default, RNF onValueChange returns an object in following format:
{ formattedValue: '$23,234,235.56', value: '23234235.56', floatValue: 23234235.56 }

React-Widget DateTimePicker errors

I cannot seem to get DateTimePicker from React-Widgets to work correctly.

If you open this codesandbox, you will see there are console errors.
https://codesandbox.io/s/react-hook-form-hookforminput-xfrup

The errors appear to be about the component expecting the 'value' to be a javascript Date.
Using Redux-Form, we have something like this:

value={!input.value ? null : newDate(input.value)} If I create a 'default' value with const methods = useForm({defaultValues:{DatePicker:new Date()}});

It seems to all work. The React-Widget component does support null.
I think the issue is here:
https://github.com/react-hook-form/react-hook-form-input/blob/master/src/index.tsx#L57

If it is not a checkbox - it sets it to blank - which will not parse as a date and is likely not ignored like a null is. This indeed does fix my issue. You can comment out the import of the npm react-hook-form-hookforminput in my codesandbox and uncomment the one that imports it from local file - which is a cut and paste of the source with the above small change.

Think this change is an acceptable one?

Lost selected option in Select component when value is 0

Describe the bug

When wrapping a Select component and in the options there is one with value 0 then the onChange event let the Select component with empty option selected.

For testing select in sandbox the Zero option in either MUI selecto or React Select (the sandbox was modified from original @bluebill1049 example)

Codesandbox link

https://codesandbox.io/s/react-hook-form-rhfinput-1d9yf

Already tested things

I already tested using only RHF without RHFInput and it works, so I supose it is a problem with RFHInput

Issues with RHFInput and validation

Describe the bug
When using a controlled component such as Material UI's radio group along with validation rules, validation errors are not cleared when the component is made valid

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/react-hook-form-rhfinput-vh5qc
  2. Click on the submit button straight away (notice the validation message on the form)
  3. Select one of the radio button options in order to fix the validation error
  4. Validation error message is still displayed until clicking the submit button again

Codesandbox link
https://codesandbox.io/s/react-hook-form-rhfinput-vh5qc

Expected behavior
Validation errors should disappear when the component is made valid using the default form mode of 'onChange'

Get input ref with uncontrolled form

Sandbox below:
https://codesandbox.io/s/react-79dbg?fontsize=14&hidenavigation=1&theme=dark

The code from sandbox I have a simple uncontrolled form but I need to show the input somewhere else, like this with a controlled form:

const [name, setName] = useState('')

<input
    name="name"
    variant="outlined"
    placeholder="Please type the channel name"
    value={name}
    ref={register}
    onChange={e => setName(e.target.value)}
/>

<span>This is a {name}</span>

What is the most recommended way to do this with a uncontrolled form?

RHFInput type issue with setValue

I got TS2322 error because of the type mismatch with useForm. This issue started when react-hook-form made setValue typesafe:

Type '<Name extends "firstName" | "lastName">(name: Name, value: FormData[Name], shouldValidate?: boolean | undefined) => void | Promise<...>' is not assignable to type '(name: string, value: any, trigger?: boolean | undefined) => void'.

The signature for setValue in useForm:

setValue: <Name extends FieldName<FormValues>>(name: Name, value: FormValues[Name], shouldValidate?: boolean | undefined) => void | Promise<boolean>

The signature for setValue in RHFInput:

setValue?: (name: string, value: any, trigger?: boolean) => void;

I thought RHFInput could use name property to define the type of the argument in setValue, but I'm not sure how it could be handled for the type of the value argument (FormData[Name]). I guess it wouldn't cause a type error if it remains as any.

Is it possible to make setValue's name argument typesafe? Or do you have a suggestion for handling this type issue without casting or having a lot less type safety?

typescript: v3.6.3

AntD switch is not correctly if type is checkbox.

Describe the bug
When I use Antd switch with RHFInput, I think it is right to set type to checkbox. then, Switch is not working. but if type is input, it is working.

To Reproduce
Checkout below codesandbox.

Codesandbox link
https://codesandbox.io/s/rhf-input-with-antd-switch-2rdwx

Expected behavior
It should be work with type="checkbox" not type="input"

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • Chrome 78 on catalina

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
I think it is a bug. so I will create a PR for resolve this issue. can I?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.