7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JSX.IntrinsicElements["input"]をstyled-componentsにスプレッド構文で展開したときのエラー

Last updated at Posted at 2021-04-17

inputのpropsを整理していたらエラーが出たので、その解決方法を残しておきます。

前提

  • inputのprops typeをJSX.IntrinsicElements["input"]をベースに定義
  • styled-componentsを使用
import React from "react";
import styled from "styled-components";

type InputProps = JSX.IntrinsicElements["input"];
type Props = InputProps & {
  labelName: string;
};

export const AddInput: React.VFC<Props> = ({ labelName, ...inputProps }) => {
    return (
      <label>
        <span>{labelName}</span>
        <SInput {...inputProps} />
      </label>
    );
 };

const SInput = styled.input`
  border: 1px solid #ccc;
  background-color: #fff;
  padding: 5px;
`;

問題点

  • styled-components(input)にスプレッド構文でpropsを展開したときにエラー
  • styled-componentsではなく、ただのinputタグならエラー出ない
Types of property 'ref' are incompatible.
Type 'LegacyRef<HTMLInputElement> | undefined' is not assignable to type '((instance: HTMLInputElement | null) => void) | RefObject<HTMLInputElement> | null | undefined'.  TS2769

解決方法

エラーにrefがincompatibleとあったので、typeからrefを除外したところエラーが消えました。めでたし。

type InputProps = JSX.IntrinsicElements["input"];
//↓これでいけた
type InputProps = Omit<JSX.IntrinsicElements["input"], "ref">;

参考記事

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?