In this tutorial we will demonstrate how we can use component props can be used and type checked.
First create a child component which we will use in the component later.
/src/components/Foo/greeting.js
import React from 'react';
const Greeting = props => {
const { name } = props;
return (
<strong>Hello, {name}!</strong>
);
}
export default Greeting;
Import the Greeting component to the Foo component:
import Greeting from './greeting';
Render the Greeting component in the Foo component, passing in your name as a property.
remember you need to wrap multiple JSX elements in a react fragment or a wrapper div
<Greeting name="Joe Bloggs" />
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities.
PWA Studio uses prop types in the following way. Import the propTypes library to the Greeting component:
import { PropTypes } from 'prop-types';
Add type checking by assigning the special propTypes property to the Greeting component just before the export
statment.
// other code...
Greeting.propTypes = {
name: PropTypes.string
};
export default Greeting;
Try passing in an invalid prop type to the Greeting component. And check your browser console for any errors.
i.e. <Greeting name={2} />