


How to edit network responses with only chrome dev tools

Atelier Typescript Avancé

It’s important and useful to pass native HTML element attributes onto TypeScript + React components that manage and extend them.
Here’s how:
Take this simple input component which you can pass an isInvalid
prop which adds a custom CSS class:
Here it is being used in a React app:
What happens if we want this to be a password input? Hide the value? Have a minimum length? To be required?
Do we have to add all the relevant HTML attributes for our input to CustomInputProps
?
Should we create a new component?
Nope! We can use the InputHTMLAttributes interface exported from React.
React exports a set of generic interfaces that correspond to various HTML elements.
We can create a new TypeScript type
which combines our custom interface and the InputHTMLAttributes
interface.
We can use ES6 rest operator to spread any props passed into the React Input component into the element
Now we can use all the attributes available on the input element (with no type errors).
For values like className
which we are passing onto the component internally, you need to handle the aggregate manually if you want to also pass a className
as a prop.
Our final input JSX here has a mix of props typed both from the InputHTMLAttributes
type and our custom type.
Hopefully this guide helps you create more flexible, useful typesafe React components. You may use this Sandbox to play with actual code & typings demonstated in this article.
More tech articles I’ve written: