18 Prop Types - biswajitsundara/react GitHub Wiki
PropTypes are a mechanism to ensure that components use the correct data type and pass the right data
- We need to install a dependency
prop-types - In the component we import the prop-types object
- And specify the type of properties
Link.propTypes - From the parent component we are passing the correct values
- However if we change
content={123}orusers={true}in LinkList then the types won't match and result an error - The component will still be rendered however the error will be logged in console.
//Link.js
import propTypes from 'prop-types';
export const Link = (props) =>{
return (
<div>
<a href=""><h3>{props.title}</h3></a>
<p>{props.content}</p>
<p>{JSON.stringify(props.users)}</p>
</div>
)
}
Link.propTypes = {
title: propTypes.string,
content: propTypes.string,
users: propTypes.array
}
//LinkList.js
import { Link } from "./Link";
export const LinkList = () => {
const users = ['Alia','Parineeti','Katrina'];
return (
<>
<Link
title="Title 1"
content="Content 1"
users={users}
/>
<Link
title="Title 2"
content="Content 2"
users={users}
/>
<Link
title="Title 3"
content="Content 3"
/>
</>
);
};
The defaultProps is the react component property that allows us to set default values for the props argument.
- The prop-type checking is applicable to default props also
- If the property is not passed to the component then the default props will display
- For the first component it will display the actual users array as that's passed to the component
- For the second link component it will display
['Kiran']because the users property is not passed.
//Link.js
Link.defaultProps = {
users: ['kiran']
}
//LinkList.js
<Link
title="Title 2"
content="Content 2"
users={users}
/>
<Link
title="Title 3"
content="Content 3"
/>
- We can mention
isRequiredon the propTypes - If we don't pass the required properties, then component will still render
- But there will be error on console.
//Link.js
Link.propTypes = {
title: propTypes.string.isRequired,
content: propTypes.string,
users: propTypes.array
}
//LinkList.js
<Link
// title="Title 2"
content="Content 2"
users={users}
/>
//Console error
Warning: Failed prop type: The prop `title` is marked as required in `Link`, but its value is `undefined`.
at Link (http://localhost:3000/static/js/bundle.js:203:25)
at LinkList
at App