47
loading...
This website collects cookies to deliver better user experience
Cover Image by Scott Webb on Unsplash
yarn add prop-types
. Then, inside a component, explicitly define the type of a prop.import React from 'react';
import PropTypes from 'prop-types';
// A component that accepts "color" prop
function FavoriteColor({ color }) {
return <h2>My favorite Color is {color}</h2>;
}
FavoriteColor.propTypes = {
color: PropTypes.string
};
// Parent component
function App() {
return (
<div className='App'>
<FavoriteColor color={'Red'} />
</div>
);
}
export default App;
color
in the App
component. You will see the expected data type on the prop.App
component, the value of prop color
is changed to a number by mistake. The component will still render in the web browser.function App() {
return (
<div className='App'>
<FavoriteColor color={120} />
</div>
);
}
prop-types
package provide validation at run-time. Not a great developer experience (imagine large applications). Using TypeScript in a React application can make the developer experience better..tsx
file. Here is how the components will look. Notice the red squiggly line beneath the prop color
. any
.PropTypes
package offers InferProps
that enables to infer the types for an existing prop-type definition on a component. It uses the @types/prop-types
package to create type definitions.InferProps
, import it from the prop-types
library and then define type declarations on the components prop.import PropTypes, { InferProps } from 'prop-types';
function FavoriteColor({ color }: InferProps<typeof FavoriteColor.propTypes>) {
return <h2>My favorite Color is </h2>;
}
FavoriteColor.propTypes = {
color: PropTypes.string
};
type
keyword. It can be used to define prop types without using the prop-types
package.type Props = {
color: string;
};
function FavoriteColor({ color }: Props) {
return <h2>My favorite Color is {color} </h2>;
}
color
prop in the App
component. It will allow you to provide anything other than a string
value for this prop.prop-types
package, all props are optional by default. To make a prop required, you will have to use .isRequired
explicitly.type Props = {
color?: string;
};