Tips for updating component rendering in react-hook-form when validation errors change manually

Struggling to automatically update validation classes on a custom datepicker Flatpickr using React-Hook-Forms,

const { register, handleSubmit, errors, control } = useForm({
  mode: 'onChange'
})

<FormGroup>
  <Controller
    name="dateControl"
    control={control}
    defaultValue={null}
    rules={{ required: true }}
    render={({ value, onChange }) => (
      <Flatpickr
        value={value}
        onChange={onChange}
        id="hf-picker"
        options={{
          altInput: true,
          altFormat: 'F j, Y',
          dateFormat: 'Y-m-d',
          altInputClass: classnames(
            'form-control flatpickr-input',
            {
              'is-invalid': errors.dateControl && true
            }
          )
        }}
      />
    )}
  />
</FormGroup>

Despite troubleshooting, I've noticed that the component doesn't re-render when validation errors are updated by react-hooks-form. Is there a way to manually trigger a re-render instead? Thank you.

Answer №1

It seems like the issue at hand is not related to RHF. The problem lies in the options prop of the <Flatpickr /> component not being updated when the configuration changes.

If you are using the react-flatpickr package, one solution could be to pass the key prop to the component and set it to the errors object of that control. This will trigger a re-render whenever the errors for that form control change.

const isNotEmpty = (array) => array?.length > 0 || "Required";
<Controller
  name="dateControl"
  control={control}
  defaultValue={null}
  rules={{ validate: isNotEmpty }}
  render={({ value, onChange }) => (
    <>
      <Flatpickr
        key={errors.dateControl}
        value={value}
        onChange={onChange}
        id="hf-picker"
        options={{
          altInput: true,
          altFormat: "F j, Y",
          dateFormat: "Y-m-d",
          altInputClass: classnames("form-control flatpickr-input", {
            "is-invalid": !!errors.dateControl
          })
        }}
      />
      {errors.dateControl && <p>{errors.dateControl.message}</p>}
    </>
  )}
/>

https://codesandbox.io/s/react-hook-form-basic-forked-e3s5s?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

Tips for managing responsive font sizes as screen size decreases

Hey there, I could really use some assistance with a new website I've been working on. While I have experience building Joomla sites for the past 6 months, this is my first attempt at making a responsive site using media queries. You can check out th ...

Are there differences in alignment?

I'm looking to create a unique visual effect where text is aligned differently on each line, shifting left, right, center, or wherever else, with the alignment origin varying by just a few pixels. This would be perfect for adding some visual interest ...

Creating inline styles within React.js

What is the proper way to include inline CSS in react.js? <div className="p-3" style={{backgroundImage: linear-gradient(to right top,#FB0712,#124FEB)}} > I am encountering an error (Error: Expected ',', got 'right') wit ...

XSL:include is failing to function properly

Here is the configuration I have set up: <?xml version="1.0"?> <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:include href="top.xsl"/> <xsl:template match=""> Content will be placed here - i ...

How to easily deactivate an input field within a MatFormField in Angular

I've come across similar questions on this topic, but none of the solutions seem to work for me as they rely on either AngularJS or JQuery. Within Angular 5, my goal is to disable the <input> within a <mat-form-field>: test.component.h ...

Increasing the height of a jQuery div element and displaying image captions when hovering over them

There is a mysterious 3px gap between the image and the overlay, causing the overlay to extend 3px beyond the height of the image. Switching the CSS to use bottom:3px fixes the issue, but it feels like a hacky solution. The source of this spacing conundrum ...

Issues encountered in loading JavaScript with jQuery script

I am facing an issue with my jQuery script not loading correctly. When I click on the calculate button, nothing happens as expected. I made sure to copy and paste jQuery directly into the file for offline use, and also created a personal console due to res ...

Font sizes for inline elements can be customized with gaps

Having trouble with setting font-size styles for inline elements, causing unexpected gaps to appear. Despite finding related questions on this issue, I have yet to discover a solution that fits my specific case. Here is the code in question: <!docty ...

Special design of a compact navbar (2 columns, each column including 2 rows of items)

I have designed a unique collapsed bootstrap navbar that showcases my menu items and social media icons in two separate sets. When expanded, everything looks great across all browsers, including IE11. However, when collapsed, the layout seems to be slight ...

Building a React Router powered Backend API

Within my application, I have an Express backend that serves a Login page to users as part of a React App. The app includes a button that guides users through Google's O-Auth process, returning user information in the following manner: router.get("/g ...

The unique design of the list extends beyond the boundary line

In my current project, I am utilizing next.js and MUI (material-ui). The component I am working with has the following structure: <Paper> <List> .. </List> </Paper> One issue I am facing is that when the list is scrolled, the ...

Is the strange z-index behavior causing issues with mouse interactions a bug or a standard occurrence?

Whenever I attempt to adjust the z-index on my webpage to rearrange the layering of overlapping divs, I always encounter an issue where the lower div becomes unresponsive to mouse events. Currently, my setup includes: <div class="leftcolumn"> <d ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

providing the context for the hover title description

I seem to be struggling with a seemingly simple issue and can't find a solution. Below is the code I have written: <html> <head> <style> span.dropt { border-bottom: thin dotted; background:white; } </style> </head> ...

Tips for concealing overflowing CSS content

How can I prevent CSS content from overflowing? I am trying to display a price tag in the CSS element, but it is protruding out of my card. .content{ content:''; position: absolute; left: 309px; ...

Moving Image Progress Indicator

I am currently developing a progress bar animation that is designed to animate from 0 to a specified percentage when the progress bar becomes visible within the browser's viewport. The animation must always trigger when the element is scrolled into vi ...

React material-ui tablecell's onclick functionIncorporating onClick functionality into a React

I am trying to implement popovers that appear when a table cell in a Material UI table is clicked. I attempted to add an onclick function to the cell, but I am struggling to pass the element value to the function. How can I solve this issue? Below is a cod ...

Currently at the beginning stages of mastering CSS and encountering difficulties with the display property

I am facing an issue with my code .name-bar, .email-bar { border-color: gray; border-style: solid; display: inline-block; } .email-bar { margin-top: 5px; } .div-one, .div-two { border-color: gray; border-style: solid; width: 200px; h ...

How to create a gelatin-like effect on a rectangle using HTML5 canvas

Currently, I'm working on a platformer game project in JavaScript. The concept involves players as rectangles jumping on and off platforms. While the basic functionality is set up, I'm now aiming to incorporate a unique 'gelatine effect&apos ...