bloomer icon indicating copy to clipboard operation
bloomer copied to clipboard

Can't set ref to <Input>

Open Kaisaurus opened this issue 6 years ago • 5 comments

I am unable to set a ref to a Input, which I want to use to focus() on it.

It seems to be because Input is not declared as a class. (which is required to set refs)

<Input
  isColor={emailWarning && 'danger'}
  type="email"
  placeholder="[email protected]"
  name="email"
  value={email}
  onChange={this.handleEmailChange}
  ref={input => {
    this.emailInput = input
  }}
/>

Kaisaurus avatar Mar 28 '18 07:03 Kaisaurus

Hi, sorry for the late answer.

You're right, we need to fix this. I'll work on it.

AlgusDark avatar Apr 18 '18 01:04 AlgusDark

Still not working?

sergiandreplace avatar May 28 '18 17:05 sergiandreplace

No, sorry, I moved to another country and I'm starting everything for new version now that I have a PC

AlgusDark avatar Jun 27 '18 04:06 AlgusDark

Hey @AlgusDark

I'm experiencing the same issue as stated above, so I consider the case still to be ongoing.

import { Input } from "bloomer";
const inputRef = React.createRef();
<Input id="name" type="name" ref={inputRef} />
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Here's an example setup: https://codesandbox.io/s/black-thunder-8enky?fontsize=14


I did stumbled upon this problem while trying to integrate Bloomer with React Hook Form

The main mechanism to link that lib is using the register method as follows:

import useForm from "react-hook-form";
import { Input } from "bloomer";

function App() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => {
    console.log(data);
  };
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label>Example</label>
      <Input name="example" defaultValue="test" ref={register} />
      <input type="submit" />
    </form>
  );
}

Here's an integrated example: https://codesandbox.io/s/react-hook-form-get-started-1z7bw?fontsize=14&hidenavigation=1&theme=dark

Any assistance on closing this topic will be appreciated :bowing_man:

kachar avatar Nov 17 '19 09:11 kachar

Sorry @kachar , the problem is that we don't have react forward ref in the components.

I decided to rewrite the library to be more friendly. The quickest solution would be to start wrap the components in a forward ref, but my main focus is to rewrite the library as there are some utils that we don't need and could be done with stronger Types with TS and let the user to deal with errors instead of fix them. But that's something is not related in this issue.

Would you like to make the fordwardRef solution and make a PR?

AlgusDark avatar Nov 18 '19 02:11 AlgusDark