Search code examples
reactjsstyled-components

Forwarding ref with hoc styled components


I want to use forwardRef with this component but couldn't make it work. Here's the component

import { StyledInput, StyledSecondaryInput } from './style'

const handleWrapping = (Component, props) => {
  const { ...rest } = props

  return <Component {...rest} />
}

export const Input = (props) => handleWrapping(StyledInput, props)

export const SecondaryInput = (props) =>
  handleWrapping(StyledSecondaryInput, props)

Solution

  • The second argument of the function will be the ref, if it's wrapped in forwardRef.

    import { StyledInput, StyledSecondaryInput } from "./style";
    import { forwardRef } from "react";
    
    const handleWrapping = (Component, props) => {
      const { forwardedRef, ...rest } = props;
    
      return <Component {...rest} ref={forwardedRef} />;
    };
    
    export const Input = forwardRef((props, ref) =>
      handleWrapping(StyledInput, { forwardedRef: ref, ...props })
    );
    
    export const SecondaryInput = forwardRef((props, ref) =>
      handleWrapping(StyledSecondaryInput, { forwardedRef: ref, ...props })
    );