Search code examples
javascriptreactjsinputfocus

Why inputRef in CurrencyTextField return the error inputRef.current is null?


I'm trying to focus on the second 'CurrentTextField' after the first 'CurrentTextField' change your value, but return the error 'inputRef.current is null'

import React, {useRef } from 'react';
import CurrencyTextField from "@unicef/material-ui-currency-textfield";

export default function Clientes() {
   let refInput = useRef(null)

   return(
      <div>
         <CurrencyTextField 
          onChange={(e) => refInput.current.focus()}
         />

         <CurrencyTextField 
          inputRef={refInput}
         />
      </div>
   )
}

Solution

  • UPDATE 2

    I checked again and saw that uses the TextField component from material-ui/core which has a inputProps prop, so this will work

      <CurrencyTextField inputProps={{ref:refInput}} />
    

    UPDATE

    I just checked the CurrencyTextField source code and it doesn't handle refs


    Since you are using the custom component CurrencyTextField you should check if it handles references, when using normal HTML tags you would use the prop ref

    export default function Clientes() {
       let refInput = useRef(null)
    
       return(
          <div>
             <CurrencyTextField 
              onChange={(e) => refInput.current.focus()}
             />
    
             <-- normal input will work -->
             <input  
              ref={refInput}
             />
          </div>
       )
    }
    

    Try to do it like if it were a regular HTML tag to see if it works.