Search code examples
reactjsalertreact-hooksreactstrap

Autofocus on reactstrap alerts using react functional component


I am using react hooks for my frontend designs and while creating a register form I have used various validations and I am depicting errors using reactstrap warning alerts. And things are working fine but when focus is not implemented on these alers means when my page shows any of alert, it doesn't focus on that automatically.

I have tried basic codes for autofocus/ autoFocus or Focus() but nothing is working as per need. My alert code look as shown below:

  {
        showAlreadyRegisteredAlert?
        <Alert variant="warning" onClose={() => setShowAlreadyRegisteredAlert(false)} dismissible>
        <p className="mb-0">
        {content}
        </p>
      </Alert>
        :null
      }

I am just writing these alert codes in between my form inputs and whenever I need to call any of them I simply setValue for the commponent and alert box is called but still it lacks autofocus.

Any help will be appreciated. Thanks in advance!


Solution

  • I found the desired solution as I wanted my page should automatically focused on appearing alert boxes. I searched react-hooks official documention and get to know that we can use "useRef" for the purpose and below is my code for better understanding and clarification:

    First: import useRef from react.

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

    Second: create const with desired name using useRef as null.

    const inputUser = useRef(null);
    

    Third: set focus on your ref const after alert.

    setShowAlreadyRegisteredAlert(true);
    inputUser.current.focus();
    

    Fourth: pass ref as const which you defined in step 2 inside your input field.

        ref= {inputUser}