haoxins / react-flatpickr

flatpickr for React
MIT License
598 stars 102 forks source link

Set id on visible input #187

Closed aviemet closed 2 years ago

aviemet commented 2 years ago

Sorry if this is noted somewhere, I searched around but couldn't find it. I'd like to set an id value on the visible input to match the for value on the corresponding label. Any instructions would be appreciated. Currently adding id to the Flatpickr element sets it on the hidden input.

This is for the React version of the component.

Thank you

jacobmischka commented 2 years ago

I think it should work as-is, maybe you're doing something else that's interfereing?

https://codesandbox.io/s/romantic-mclean-wtyvlc?file=/src/App.js

https://user-images.githubusercontent.com/3939997/165585120-2c1ac400-87ed-4a3f-924f-7b02f02bc881.mp4

You can also use the render prop if you want more flexibility.

aviemet commented 2 years ago

Just did a quick test of all the options I was passing to the component I'm using. Looks like it only happens when using the altInput option. In that case, a hidden input is added to generated html and the id is applied to that instead of the visible input.

Edit: Added an example to the codesandbox you created

jacobmischka commented 2 years ago

Ah, yeah that'll happen. https://github.com/flatpickr/flatpickr/issues/2110

You will either need to not use altInput and use something like the render prop to do it yourself, wrap the input with a label instead of using id, or manually add the ID imperatively with refs. Closing because this is an upstream issue as linked above.

aviemet commented 2 years ago

Got it, thanks for pointing me in that direction, I was able to find a simple way to do this by poking around in the flatpickr source.

Looks like they built a solution for this, but haven't documented it yet. They created a plugin aptly named labelPlugin which addresses exactly this issue. I'll plop it down here for posterity:

import Flatpickr from 'react-flatpickr'
import labelPlugin from 'flatpickr/dist/plugins/labelPlugin/labelPlugin'

const ExampleComponent = () => (
  <Flatpickr options={ { 
    altInput: true,
    plugins: [labelPlugin()]
  } } />
)
jacobmischka commented 2 years ago

Oh great, thanks for following up with that!