Handle a custom component using React Hook Forms and React Table

Viewed 1436

I'm trying to set up a custom component to my react-hook-forms and react-table

const selectedUserIds =  watch(`user_ids`) || [];

<Controller
  control={control}
  name={fieldName("user_ids")}
  render={({ field: { value, onChange } }) => (
  <UserTable selectedUserIds={selectedUserIds} updatePropertySelection={onChange}/>
)}
/>

UserTable:

function updatePropertyTableSelection(ids){
  const ids = extractIds(ids);
  updatePropertySelection(ids);
}

const selectedUserIdsForTable = convertIdsToTableFormat(selectedUserIds)
return (
<React.Fragment>
    <BasicTable
        tableHeader={() => null}
        columns={[
          {
            Header: "User Name",
            accessor: "attributes.name",
          }
        ]}
        data={data}
        selectedRows={selectedUserIdsForTable}
        onSelectedRowsChange={updatePropertyTableSelection}
      />
</React.Fragment>
)

When I associate the onChange handler to updatePropertySelection I get stuck in an infinite rerender. How should I prevent that?

1 Answers

I faced the same issue and I fix it by following this:

  1. First one, my issue comes from the old react-hook-form, now I'm using ^7.14.2 and its resolve issue.

  2. Second solution fixed issue by replacing onChange to field.onChange for example (from real project):

    <Controller
      name={"explanation"}
      control={props.control}
      render={({field}) => {
        return (
          <MyEditor
            placeholder={t("onlineAssessments.question.explanationPlaceholder")}
            onPressEnter={props.onPressEnter}
            onChange={(val, editor) => {
                // notify parent 
                field.onChange(val);
    
                // calc count
                setExplanationCount(editor?.getBody().innerText.trim().length)
              }
            }
          />
        )
      }
      }
    /> 
    

and I think this change comes from the latest update..

  1. May you have something keep re-render trigger, base on your table, you may need to useCallBack or useMemo to prevent re-render on each visit else if dependency change, for example:

    const updatePropertyTableSelection = useCallBack((ids) => {
      const ids = extractIds(ids);
      updatePropertySelection(ids);
    }, []);
    

    and

    const selectedUserIdsForTable = useMemp(() => { convertIdsToTableFormat(selectedUserIds)
    }, []);
    

Note: Don't forget to update dependency only if it's needed and only to what you needed to re-render

Related