y2UcDgAL
y2UcDgAL

Reputation: 41

Why can't I pass props when I use "input type" in React + Styled-components?

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
`;

Upvotes: 0

Views: 1006

Answers (1)

aleksxor
aleksxor

Reputation: 8360

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/[email protected] version:

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

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

@types/[email protected] 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" />
);

Upvotes: 1

Related Questions