use ref hooks Input component


Topic: use ref hooks Input component

nachomartinez30 asked 5 years ago

hi! how can i use a ref hook in a Input element?

this doesn't work:

 const myRef = useRef('')
...
        <MDBInput
            inputRef={ref=>myRef=ref}
        />

Jakub Chmura staff premium answered 5 years ago

Hi @nachomartinez30,

You don't need to initiate ref on input because input has already initiated a reference.

Here is a snippet.

import React from 'react';
import { MDBInput } from 'mdbreact';

const Input = props => {
  return (
    <MDBInput
      label='My input'
      name='refInput'
      value='testValue'
      inputRef={e => console.log(e.value)}
      type='text'
      icon='user'
    />
  );
};

export default Input;

Best, Kuba


mbdtsmh commented 5 years ago

I believe the Typescript types for the function signature are incorrect.

inputRef?: | RefObject<HTMLInputElement> | ((ref: RefObject<HTMLInputElement>) => void) | null;

So the object ref would need to be accessed via ref.current but the type being passed appears to be HTMLInputElement


Piotr Glejzer staff commented 5 years ago

Yea, I think you are right.


Hi @nachomartinez30,

You use inputref for access to ref and ref attributes e.g tabIndex:

    <MDBInput
  inputRef={ref => ref.tabIndex = "1"}
  type='text'
/>

Jakub Chmura staff premium commented 5 years ago

You do it wrong. You need to use a function that will be changing everything inside of it.

example:

import React from 'react';
import { MDBInput, MDBBtn } from 'mdbreact';

const InputPage = () => {
  let thisIsAReference = '';

  const myRefFunction = (ref) => {
    thisIsAReference = ref;
  };

  const changeVal = () => {
    thisIsAReference.value = thisIsAReference.value + '1';
  };

  return (
    <>
      <MDBInput
        label='My input'
        name='refInput'
        value='testValue'
        inputRef={myRefFunction}
        type='text'
        icon='user'
      />
      <MDBBtn onClick={changeVal}>Change input val</MDBBtn>
    </>
  );
};

export default InputPage;

behzad soleimani commented 5 years ago

for tabIndex? i need a tabIndex props. only way for that is to use inputref


Jakub Chmura staff premium commented 5 years ago

You can get access to tabIndex using this ref from the example above.


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 4.22.1
  • Device: CPU
  • Browser: Chrome
  • OS: Windows
  • Provided sample code: No
  • Provided link: No