Home > Mobile >  Add a date-picker to the DOM dynamically using 'react-datepicker'
Add a date-picker to the DOM dynamically using 'react-datepicker'

Time:08-19

I have a date-picker in React.js and I'm using the library 'react-datepicker'. I can use this as expected by following the documentation, however I have a special use case that seems to make this library not useable. Essentially I want to add a date picker to select a start and end date, but It's a special case because this form doesn't load up when the component does. There's some event, let's say a button click, that happens and then I dynamically add the DatePicker's onto the DOM. Is this possible with this react library? Attached is a sandbox that shows the problem. codesandbox.com/

CodePudding user response:

please using the react-multi-date-picker package This package offers good features It may solve your problem

CodePudding user response:

Solved:

I ended up creating a new component just for the DatePicker, and this solved the issues. I also ended up using MUI [MUI][1] and their datepicker. Here's what the component looked like once I got things working.

import React, { useState } from "react";
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker';

function DatePicker(props) {
    const [ value, setValue ] = useState( props.date );

    const handleChange = ( newValue ) => {
        console.log("newValue: ", newValue );
        setValue(newValue);
        props.setDate( newValue );
    };

  return (
    <>
        <LocalizationProvider dateAdapter={AdapterDateFns}>
            <Stack spacing={3}>
                <DesktopDatePicker
                    label={ props.display }
                    inputFormat="MM/dd/yyyy"
                    value={ value }
                    onChange={ handleChange }
                    renderInput={(params) => <TextField {...params} />}
                />
            </Stack>
        </LocalizationProvider>
    </>
  );
}

export default DatePicker;

`


  [1]: https://mui.com/x/react-date-pickers/getting-started/
  • Related