0

I am learning React. I want to use styled-components to style "input type". I can expand props with normal "input type". But when I use styled-components, it doesn't work.. props are passed from the parent component.

import * as React from "react";
import { Input } from "./style";

export const Field: React.FC<React.ComponentProps<"input">> = (
  props: React.ComponentProps<"input">
) => (
  <>
      {/* work */}
    {/* <input {...props} type={"text"} /> */}

      {/* it doesn't work.. */}
      <Input {...props} type={"text"} />     
  </>
);

style.ts

import styled from "styled-components";

export const Input = styled.input`
 //style
`;
aleksxor
  • 7,535
  • 1
  • 22
  • 27
y2UcDgAL
  • 31
  • 6

1 Answers1

1

The problem is native input and Input have incompatible ref property types. While native input ref has type

LegacyRef<HTMLInputElement> | undefined

styled-components wrapped Input has ref type

((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined

You may just omit this property if you're not going to pass it to the component:

export const Field: React.FC<React.ComponentPropsWithoutRef<"input">> = (
  props
) => (
    <Input {...props} type="text" />
);

or type it correctly:

@types/react@17.x version:

type Props = React.ComponentPropsWithoutRef<"input"> & { ref: React.ForwardedRef<HTMLInputElement> }

export const Field: React.FC<Props> = (props) => (
  <Input {...props} type="text" />
);

@types/react@16.x version:

// there is no exported ForwardedRef type and we have to define it oursevles
type ForwardedRef<T> = ((instance: T | null) => void) | React.MutableRefObject<T | null> | null
type Props = React.ComponentPropsWithoutRef<"input"> & { ref: ForwardedRef<HTMLInputElement> }

export const Field: React.FC<Props> = (props) => (
  <Input {...props} type="text" />
);
aleksxor
  • 7,535
  • 1
  • 22
  • 27