akibo
akibo

Reputation: 715

spread props in react using typescript

When I first started to adapt typescript in react, I notice I can't using ...props, as typescript check every single prop that are passed in the components. It's great but it's also annoying, where I have to pass native props like id, name etc declaratively as props.


interface MyComponentProps {
  name: string,
  id: string,
  placeholder: string
}

const MyComponent = ({
  name,
  id,
  placeholder
}: MyComponentProps) => {
  return <input type="text" placeholder={placeholder} name={name} id={id}/>
}
export default function App() {
  return (
    <div className="App">
      <MyComponent placeholder="Name" name="something" id="myInput" />
    </div>
  );
}

Upvotes: 2

Views: 3457

Answers (2)

wentjun
wentjun

Reputation: 42576

You should edit your interface such that it is extending the props of the HTML input element:

interface MyComponentProps extends InputHTMLAttributes< HTMLInputElement>)  {
  // add other custom props
}

const MyComponent: React.FC<MyComponentProps> = (props) => (...)

Upvotes: 4

Mark  Partola
Mark Partola

Reputation: 674

You can explicitly cast it to HTMLAttributes

Declare an interface like union of component's props with HTMLAttributes

interface MyComponentProps = {}

const MyComponent: React.FC<MyComponentProps & HTMLAttributes>...

Detailed explanation you can find here: https://stackoverflow.com/a/40032869/4186110

Upvotes: 0

Related Questions