Home > Back-end >  useLayoutEffect is not working properly. What is the error?
useLayoutEffect is not working properly. What is the error?

Time:02-11

Error Generated here:

    useLayoutEffect(()=>{
        const reInput = document.getElementById('confpassword');
        
        reInput.onkeydown = function () {
            document.getElementById('messageCheck').style.display = "block";
        }
        reInput.onblur = function () {
            document.getElementById('messageCheck').style.display = "none";
        }
    })

My Input field is associated with it...

<RStyle.Detailsform id="confpassword" type={confirmpassInputType} name="conf-password" minLength="8" required onChange={inputChange} onKeyDown={confirmPassChange}/>

My Error Message Div

<RStyle.ErrorMessageCont>
  <RStyle.ErrorMessage1 id="messageCheck">
    <p id="passCheck" className="invalid">
       <VscError className='errorIcon' style={errorIcon} />
       <VscCheck className='validIcon' style={validIcon} /> Password's Match
    </p>
  </RStyle.ErrorMessage1>
</RStyle.ErrorMessageCont>

Error Message

CodePudding user response:

When using React, the way events are handled are slightly different than classic js, as instead of performing actions directly to the DOM you would do them through the virtual DOM instead.

Here's the equivalent of what you want to achieve, in React standards:

import { useState } from 'react';

const Component = () => {
  /** 
   * Here you essentially set the state of the component
   * @see https://reactjs.org/docs/hooks-intro.html
   */
  const [showErrorMessage, setShowErrorMessage] = useState(false);

  /** 
   * Here we set the state of the error message on true,  
   * so to display it with the condition below (showErrorMessage && ( .. ))
   */
  const handleOnKeyDown = () => {
    setShowErrorMessage(true);
    confirmPassChange();
  };

  /** 
   * Here we set the error message state on false so to hide it onBlur
   */
  const handleOnBlur = () => {
    setShowErrorMessage(false);
  };

  return (
    <>
      {showErrorMessage && (
        <RStyle.ErrorMessageCont>
          <RStyle.ErrorMessage1 id="messageCheck">
            <p id="passCheck" className="invalid">
              <VscError className="errorIcon" style={errorIcon} />
              <VscCheck className="validIcon" style={validIcon} /> Password's Match
            </p>
          </RStyle.ErrorMessage1>
        </RStyle.ErrorMessageCont>
      )}

      <RStyle.Detailsform
        id="confpassword"
        type={confirmpassInputType}
        name="conf-password"
        minLength="8"
        required
        onChange={inputChange}
        onKeyDown={handleOnKeyDown}
        onBlur={handleOnBlur} // Note the events are listened directly from the component
      />
    </>
  );
};
  • Related