akibo
akibo

Reputation: 715

typescript spread operator for props in react throw error

When using typescript with react, I want to skip passing every single props especially native props for HTML like id, name, placeholder etc but I got error on my {...props}

I've extended my interface with InputHTMLAttributes so that typescript didn't check my props but it still got unresolved error

import React, { InputHTMLAttributes } from "react";
import "./styles.css";

interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
  nonNativeProp: string;
  props: object
}

const MyComponent: React.FC<MyComponentProps> = ({
  nonNativeProp,
  props
}) => {
  return <input type="text" {..props} />;
};

export default function App() {
  return (
    <div className="App">
      <MyComponent
        nonNativeProp="abc"
        placeholder="Name"
        name="something"
        id="myInput"
        data-custom="custom-attr"
      />
    </div>
  );
}

https://codesandbox.io/s/elegant-forest-42t4b?file=/App.tsx

Upvotes: 1

Views: 1458

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281606

First of all, you need to use rest spread syntax to get props and not destructure like an object

Secondly interface needn't define props as an object

Lastly you have {..props} instead of {...props}. Notice 3 dots before props

interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
  nonNativeProp: string;
}

const MyComponent: React.FC<MyComponentProps> = ({
  nonNativeProp,
  ...props
}) => {
  return <input type="text" {...props} />;
};

export default function App() {
  return (
    <div className="App">
      <MyComponent
        nonNativeProp="abc"
        placeholder="Name"
        name="something"
        id="myInput"
        data-custom="custom-attr"
      />
    </div>
  );
}

Working demo

Upvotes: 6

Related Questions