React - displaying verification fails messages with State and Props

0 votes
46 views
added Feb 22 in React by lcjr First Warrant Officer (11,850 points)

With this setup, if the OTP verification fails, the parent component sets the verificationMessage state to 'Oops! Invalid OTP.', and this message is passed down to the OtpListing component as the errorMessage prop. The OtpListing component then renders this error message below the OTP input fields.

Parent (through State)

const [verificationMessage, setVerificationMessage] = useState('');

// Define function to handle OTP verification
const handleOtpVerification = (otp) => {
  // Perform OTP verification logic here
  if (otp === '1234') {
    console.log('OTP verified successfully!');
    // Set apiResponseValue accordingly
    setApiResponseValue(0); // Assuming OTP verification success results in apiResponseValue being 0
  } else {
    console.log('OTP verification failed!');
    // Set verification message
    setVerificationMessage('Oops! Invalid OTP.');
    // Don't update apiResponseValue
    return;
  }
};

return (
  <div>
    {apiResponseValue === 0 ? (
      <OtpListing 
        onOtpSubmit={handleOtpVerification}
        errorMessage={verificationMessage} 
      />
    ) : (
      <ContactFormComponent
        isMobile={true}
      />
    )}
  </div>
);

 

In the ChildComponent component, you need to update it to accept an errorMessage prop:

import React, { useState, useRef } from 'react';

const ChildComponent = ({ onOtpSubmit, errorMessage }) => {
  const [otp, setOtp] = useState(['', '', '', '']);
  const inputRefs = [useRef(), useRef(), useRef(), useRef()];

  const resendOtpListing = () => {
    // Your logic for resending OTP
    console.log('Resend OTP');
  };

  return (
    <div className='otpListing_wrapper'>
      <div className="otp_enquiryForm">
        // your otp code goes here
      </div>
      <div className="errors">
        {otp.some((value) => value === '') && (
          <p className="error-msg">Please enter a valid OTP.</p>
        )}
        {errorMessage && <p className="error-msg">{errorMessage}</p>}
      </div>
      <button onClick={handleSubmit}>Submit</button>
      <div>Didn't receive the code? <b onClick={resendOtpListing}>Resend</b></div>
    </div>
  );
};

export default ChildComponent;
lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...