Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to use ref attribute on some components #69

Open
nbetts opened this issue Jan 29, 2021 · 4 comments
Open

Unable to use ref attribute on some components #69

nbetts opened this issue Jan 29, 2021 · 4 comments
Labels
bug Something isn't working good first issue Good for newcomers

Comments

@nbetts
Copy link

nbetts commented Jan 29, 2021

Hi, I am unable to use the ref attribute on some components where I need it, such as the Select component (because it's an input) and the ErrorSummary component (to focus on it when it appears). If I try to use the ref attribute I get the following React error:

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

The Input component achieves ref forwarding this by including an innerRef attribute to forward the ref to the input. I think this should work on the other components too (and I presume all input-like components should do this)?

@kevinkuszyk
Copy link
Contributor

Hi @nbetts, can you post some sample code to reproduce this?

@nbetts
Copy link
Author

nbetts commented Feb 2, 2021

Sure:

import { Input, Select } from 'nhsuk-react-components';
import { useRef } from 'react';

const MyComponent = () => {
  const inputRef = useRef(null);
  const selectRef = useRef(null);

  // inputRef is a prop on the NHS input component and correctly forwards the ref to the underlying input element.
  // The NHS select component lacks an inputRef, and trying to use the normal ref is not allowed by React (see warning in post). 
  return (
    <>
      <Input inputRef={inputRef} />
      <Select ref={selectRef} />
    </>
  );
};

export default MyComponent;

React recommends forwarding refs using React.forwardRef, especially for reusable component libraries: https://reactjs.org/docs/forwarding-refs.html

@Tomdango Tomdango added bug Something isn't working good first issue Good for newcomers labels Feb 3, 2021
@kevinkuszyk
Copy link
Contributor

@dominicjameskelly is this the same issue we're seeing with some of our custom form components?

/cc @ramyas16

@dom-kelly
Copy link

@dominicjameskelly is this the same issue we're seeing with some of our custom form components?

/cc @ramyas16

It sounds like it, yep.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working good first issue Good for newcomers
Projects
None yet
Development

No branches or pull requests

4 participants