javascriptreactjsmaterial-uimui-x

Retrieving input value on submit in mui joy library returns "unidentified"


I am attempting to get 2FA user input to authenticate access but I am having trouble retrieving data from the mui JoyUI library. I tried e.target and searched for the input value but no luck. I am missing something in the documentation. I also tried using 'useRef' and this code is for this attempt (useRef). Its returning authCode is returning undefined.

import React, { useRef } from "react";

import { Paper, Typography } from "@mui/material";
import {
  Modal,
  ModalClose,
  ModalDialog,
  DialogTitle,
  DialogContent,
  Stack,
  FormControl,
  Input,
  Button,
} from "@mui/joy";

const WeaModal = ({ status, modalAction }) => {
  console.log("IN MODAdL " + status);
  let inputRef = useRef(null);
  const sendAuthCode = (event) => {
    event.preventDefault();
    const authCode = inputRef.current.value;
    console.log(authCode);
  };
  return (
    <Modal
      open={status}
      onClose={() => modalAction(false)}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
    >
      <Paper>
        <ModalDialog>
          <ModalClose variant="plain" sx={{ m: 1 }} />
          <DialogTitle>Authentication</DialogTitle>
          <DialogContent>Please Enter Your 2FA Code</DialogContent>
          <form onSubmit={sendAuthCode}>
            <Stack spacing={2}>
              <FormControl>
                <Input ref={inputRef} autoFocus required />
              </FormControl>
              <Button type="submit">Submit</Button>
            </Stack>
          </form>
        </ModalDialog>
      </Paper>
    </Modal>
  );
};

export default WeaModal;

Solution

  • According to the docs You need to set ref of MUI Joy input like this:

    <Input
      slotProps={{
        input: {
          ref: inputRef,
        },
      }}
      autoFocus
      required
    />
    

    You can take a look at this Stackblitz for a live working example of your sample code.