1

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

1
  • 1
    Probably a typho.. you should have 3 dots and not 2 dots in the spread operator Commented May 7, 2020 at 7:09

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

you said interface need to define prop as object, but I didn't see any warning when you leave it empty?
Sorry that was a typo on my part which completely changed the meaning. What I meant was interface need not define props as an object. Updated the post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.