ConfirmationCodeInput - goobz22/goobs-frontend GitHub Wiki

ConfirmationCodeInput Component

The ConfirmationCodeInput component in goobs-frontend is a specialized input field designed for entering confirmation codes, often used in two-factor authentication (2FA) or one-time password (OTP) scenarios. It provides a user-friendly interface for entering multi-digit codes with individual input fields for each digit.

Importing the Component

To use the ConfirmationCodeInput component in your project, import it from the goobs-frontend package:

import { ConfirmationCodeInput } from 'goobs-frontend';

Basic Usage

Here's a basic example of how to use the ConfirmationCodeInput component:

import React, { useState } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';

const ConfirmationCodeExample: React.FC = () => {
  const [isValid, setIsValid] = useState(false);

  return (
    <ConfirmationCodeInput
      isValid={isValid}
      codeLength={6}
      aria-label="Enter confirmation code"
    />
  );
};

export default ConfirmationCodeExample;

Props

The ConfirmationCodeInput component accepts the following props:

  • identifier: string (optional) - A unique identifier for the component.
  • columnconfig: columnconfig (optional) - Configuration for the component's grid column.
  • isValid: boolean (required) - Indicates whether the entered code is valid.
  • codeLength: number (optional, default: 6) - The number of digits in the confirmation code.
  • aria-label: string (optional) - Accessibility label for the entire input group.
  • aria-required: boolean (optional) - Indicates if the input is required for accessibility purposes.
  • aria-invalid: boolean (optional) - Indicates if the input is invalid for accessibility purposes.

Features

  1. Individual Input Fields: The component renders separate input fields for each digit of the confirmation code.
  2. Auto-focus: As the user types, the focus automatically moves to the next input field.
  3. Validation Indicator: A visual indicator shows whether the entered code is valid or not.
  4. Keyboard Navigation: Users can navigate between input fields using arrow keys.
  5. Accessibility: The component includes proper ARIA attributes for improved accessibility.

Styling

The ConfirmationCodeInput component comes with default styling to provide a consistent appearance. However, you can customize its look using the sx prop or styled-components. Here's an example of custom styling:

import React, { useState } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';
import { Box } from '@mui/material';

const StyledConfirmationCodeExample: React.FC = () => {
  const [isValid, setIsValid] = useState(false);

  return (
    <Box sx={{ maxWidth: '400px', margin: '0 auto' }}>
      <ConfirmationCodeInput
        isValid={isValid}
        codeLength={4}
        aria-label="Enter 4-digit code"
        sx={{
          '& input': {
            width: '50px',
            height: '50px',
            fontSize: '24px',
            textAlign: 'center',
            marginRight: '8px',
            borderRadius: '8px',
            border: '2px solid #3f51b5',
            '&:focus': {
              outline: 'none',
              boxShadow: '0 0 0 2px rgba(63, 81, 181, 0.5)',
            },
          },
          '& .validation-indicator': {
            width: '24px',
            height: '24px',
            borderRadius: '50%',
          },
        }}
      />
    </Box>
  );
};

export default StyledConfirmationCodeExample;

Advanced Usage

Custom Validation Logic

You can implement custom validation logic for the confirmation code:

import React, { useState, useEffect } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';

const CustomValidationExample: React.FC = () => {
  const [code, setCode] = useState('');
  const [isValid, setIsValid] = useState(false);

  useEffect(() => {
    // Custom validation logic
    const validateCode = (inputCode: string) => {
      // Example: Code is valid if it's "123456"
      return inputCode === "123456";
    };

    setIsValid(validateCode(code));
  }, [code]);

  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
  };

  return (
    <ConfirmationCodeInput
      isValid={isValid}
      codeLength={6}
      aria-label="Enter 6-digit code"
      onChange={handleCodeChange}
    />
  );
};

export default CustomValidationExample;

Integration with Form Submission

You can integrate the ConfirmationCodeInput component with a form submission process:

import React, { useState } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';
import { Button, Box, Typography } from '@mui/material';

const FormSubmissionExample: React.FC = () => {
  const [code, setCode] = useState('');
  const [isValid, setIsValid] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
    setIsValid(newCode.length === 6); // Simple validation
  };

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    if (isValid) {
      // Perform submission logic here
      console.log('Submitting code:', code);
      setIsSubmitted(true);
    }
  };

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ maxWidth: '400px', margin: '0 auto' }}>
      <Typography variant="h6" gutterBottom>
        Enter Confirmation Code
      </Typography>
      <ConfirmationCodeInput
        isValid={isValid}
        codeLength={6}
        aria-label="Enter 6-digit confirmation code"
        onChange={handleCodeChange}
      />
      <Button
        type="submit"
        variant="contained"
        color="primary"
        disabled={!isValid}
        sx={{ mt: 2 }}
      >
        Submit Code
      </Button>
      {isSubmitted && (
        <Typography color="success" sx={{ mt: 2 }}>
          Code submitted successfully!
        </Typography>
      )}
    </Box>
  );
};

export default FormSubmissionExample;

Accessibility

The ConfirmationCodeInput component is designed with accessibility in mind:

  1. It uses proper aria-label attributes to describe the purpose of the input.
  2. Each input field is properly labeled for screen readers.
  3. Keyboard navigation is supported for moving between input fields.

To further enhance accessibility:

  1. Provide clear instructions before the input field, explaining what the code is for and where the user can find it.
  2. Use the aria-required and aria-invalid props when appropriate to communicate the input's state to assistive technologies.

Best Practices

  1. Clear Instructions: Provide clear instructions on where the user can find the confirmation code (e.g., "Check your email for a 6-digit code").
  2. Error Handling: Implement clear error messages for invalid codes or when the maximum number of attempts is reached.
  3. Resend Option: If applicable, provide an option to resend the confirmation code.
  4. Timeout: Consider implementing a timeout for the confirmation code and display a countdown timer if appropriate.
  5. Mobile Optimization: Ensure the component works well on mobile devices, considering touch interactions and on-screen keyboards.
  6. Security: Be mindful of security implications. Don't store or log the full confirmation code on the client-side.

Performance Considerations

The ConfirmationCodeInput component is relatively lightweight, but consider the following for optimal performance:

  1. Debounce Validation: If you're performing server-side validation, consider debouncing the validation calls to reduce unnecessary network requests.
  2. Memoization: If the component is used in a complex form with frequent re-renders, consider wrapping it with React.memo to prevent unnecessary re-renders.
import React, { memo } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';

const MemoizedConfirmationCodeInput = memo(ConfirmationCodeInput);

const PerformantCodeInput: React.FC = () => {
  // ... other logic

  return (
    <MemoizedConfirmationCodeInput
      isValid={isValid}
      codeLength={6}
      aria-label="Enter 6-digit code"
    />
  );
};

export default PerformantCodeInput;

Troubleshooting

  1. Code Not Auto-Advancing: Ensure that the codeLength prop matches the number of input fields you expect. If auto-advancing isn't working, check if there are any conflicting keyboard event listeners.

  2. Validation Not Updating: If the validation state isn't updating correctly, make sure you're correctly managing the isValid prop in the parent component and passing it down to the ConfirmationCodeInput.

  3. Styling Issues: If custom styles are not applying correctly, check the specificity of your CSS selectors. You may need to use more specific selectors or the !important flag in some cases.

  4. Accessibility Warnings: If you're seeing accessibility warnings in your console, ensure you're providing all necessary ARIA attributes, including aria-label, aria-required, and aria-invalid when appropriate.

Examples

Basic Example with State Management

import React, { useState } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';
import { Box, Typography } from '@mui/material';

const BasicExample: React.FC = () => {
  const [code, setCode] = useState('');
  const [isValid, setIsValid] = useState(false);

  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
    setIsValid(newCode.length === 6); // Simple validation
  };

  return (
    <Box sx={{ maxWidth: '400px', margin: '0 auto' }}>
      <Typography variant="h6" gutterBottom>
        Enter the 6-digit code sent to your email
      </Typography>
      <ConfirmationCodeInput
        isValid={isValid}
        codeLength={6}
        aria-label="Enter 6-digit confirmation code"
        onChange={handleCodeChange}
      />
      <Typography sx={{ mt: 2 }}>
        Entered code: {code}
      </Typography>
      <Typography color={isValid ? 'success.main' : 'error.main'} sx={{ mt: 1 }}>
        {isValid ? 'Valid code' : 'Invalid code'}
      </Typography>
    </Box>
  );
};

export default BasicExample;

Example with Resend Option and Timer

import React, { useState, useEffect } from 'react';
import { ConfirmationCodeInput } from 'goobs-frontend';
import { Box, Typography, Button } from '@mui/material';

const ResendExample: React.FC = () => {
  const [code, setCode] = useState('');
  const [isValid, setIsValid] = useState(false);
  const [timer, setTimer] = useState(30);
  const [canResend, setCanResend] = useState(false);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (timer > 0 && !canResend) {
      interval = setInterval(() => {
        setTimer((prevTimer) => prevTimer - 1);
      }, 1000);
    } else {
      setCanResend(true);
    }
    return () => clearInterval(interval);
  }, [timer, canResend]);

  const handleCodeChange = (newCode: string) => {
    setCode(newCode);
    setIsValid(newCode.length === 6); // Simple validation
  };

  const handleResend = () => {
    // Implement resend logic here
    console.log('Resending code...');
    setTimer(30);
    setCanResend(false);
  };

  return (
    <Box sx={{ maxWidth: '400px', margin: '0 auto' }}>
      <Typography variant="h6" gutterBottom>
        Enter the 6-digit code sent to your email
      </Typography>
      <ConfirmationCodeInput
        isValid={isValid}
        codeLength={6}
        aria-label="Enter 6-digit confirmation code"
        onChange={handleCodeChange}
      />
      <Box sx={{ mt: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Button
          onClick={handleResend}
          disabled={!canResend}
        >
          Resend Code
        </Button>
        {!canResend && (
          <Typography>
            Resend in {timer}s
          </Typography>
        )}
      </Box>
    </Box>
  );
};

export default ResendExample;

By following these guidelines and leveraging the features of the ConfirmationCodeInput component, you can create user-friendly and secure confirmation code entry experiences in your goobs-frontend projects.

Related Components

  • TextField: For general text input needs
  • Form: For creating more complex forms that might include the ConfirmationCodeInput
  • Button: Often used in conjunction with ConfirmationCodeInput for form submission

Future Enhancements

Potential future enhancements for the ConfirmationCodeInput component could include:

  1. Built-in support for different code formats (e.g., alphanumeric codes)
  2. Customizable validation indicator styles
  3. Integration with clipboard API for paste support
  4. Animated transitions between valid and invalid states
  5. Support for voice input for accessibility

Remember to check the goobs-frontend documentation for the most up-to-date information on component features and best practices.

⚠️ **GitHub.com Fallback** ⚠️