Why doesn't ref "anchor" the element to the right place?

  • 0
    There is a DatePicker component. This is the button, by clicking on which the calendar should open, to select the date. I'm using the material-ui component.
    In general, a ref is created in the parent component.

    const datePickerRef = useRef ();

    Then the ref is passed to the DatePicker component.

    <Grid item>
      <DatePicker ref={datePickerRef} autoOk value={start_at} timeZone={timeZone} onChange={handleDateChange} />
    </Grid>


    And the component itself takes the ref and passes it on to the inputComponent, which is a DateIconButton button that opens the calendar when clicked.

    const DateIconButton = forwardRef(({ onOpen }, ref) => (
      <IconButton size="small" ref={ref} onClick={onOpen}>
        <CalendarTodayIcon color="primary" fontSize="small" />
      </IconButton>
    ));
    .

    And this is how the main component looks like, DatePicker

    const DatePicker = forwardRef((props, ref) => {
      const {
        ... ,
        InputComponent = DateIconButton,
        ...rest
      } = props;
    
      const [open, setOpen] = useState(false);
    
      const handleOpen = () => {
        setOpen(true);
      };
    
      const handleClose = () => {
        setOpen(false);
        Promise.resolve().then(() => {
          if (onBlur) onBlur();
        });
      };
    
      const handleChange = value => {
        onChange(outputDateToISOString(value, timeZone));
      };
    
      useImperativeHandle(ref, () => ({
        open: handleOpen,
      }));
    
      return (
        <MuiDatePicker
          {...rest}
          open={open}
          value={inputISOStringToDate(value, timeZone)}
          onChange={handleChange}
          onClose={handleClose}
          renderInput={props => (
            <InputComponent
              {...props}
              label={label}
              placeholder={placeholder}
              helperText={helperText}
              error={error}
              value={value ? formatDate(value, 'MMMM, d, yyyy', timeZone) : ''}
              onClick={handleOpen}
              onOpen={handleOpen}
            />
          )}
        />
      );
    });


    And by clicking on the InputComponent, which is the DateIconButton, the calendar should pop up and open next to this button. But refs do not hold it, and the calendar opens in the corner of the screen, and not where it is needed.
    How to fix it?
    React Adam Howe, Oct 20, 2019

  • 0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!