Components that accept props will define the types of props they accept. This serves two purposes:
- Declare the public API of the component
- Validate the props being passed in by the parent
🏅 The goal of this step is to learn how to define prop types for a component.
As always, if you run into trouble with the tasks or exercises, you can take a peek at the final source code.
Help! I didn't finish the previous step! 🚨
If you didn't successfully complete the previous step, you can jump right in by copying the step.
Complete the setup instructions if you have not yet followed them.
Re-run the setup script, but use the previous step as a starting point:
npm run setup -- src/06-components
This will also back up your src/workshop
folder, saving your work.
Now restart the app:
npm start
After some initial compiling, a new browser window should open up at http://localhost:3000/, and you should be able to continue on with the tasks below.
Concepts | Tasks | Exercises | Elaboration & Feedback | Resources
- Type-checking props
Using the prop-types
package, add a prop type in SearchForm
for the onChange
callback prop:
import React, { Fragment, useState, useEffect } from 'react'
import PropTypes from 'prop-types' // 👈🏾 new import
...
const SearchForm = (props) => {
const { onChange } = props
...
}
// define types of props 👇🏾
SearchForm.propTypes = {
onChange: PropTypes.func.isRequired,
}
export default SearchForm
Now add a prop type in Results
for the items
prop:
import React from 'react'
import PropTypes from 'prop-types' // 👈🏾 new import
const Results = (props) => {
const { items } = props
...
}
// define types of props 👇🏾
Results.propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
rating: PropTypes.oneOf(['G', 'PG', 'PG-13', 'R']).isRequired,
previewUrl: PropTypes.string.isRequired,
}),
).isRequired,
}
export default Results
- Add make all of the props for
ResultsItem
required - Add 4 additional optional props to
SearchForm
:initialSearchQuery
,initialShowInstant
,initialRating
&initialLimit
- These will set the initial values of the corresponding state variables (
useState(XXX)
) - 🔑 HINT: Use
defaultProps
to set the default values when the props are not specified
- These will set the initial values of the corresponding state variables (
- Add some of the
initial*
props to<SearchForm />
inApp
and use the React Developer Tools to see how the initial UI changes
After you're done with the exercise and before jumping to the next step, please fill out the elaboration & feedback form. It will help seal in what you've learned.
Go to Step 8 - Search Focus.
Got questions? Need further clarification? Feel free to post a question in Ben Ilegbodu's AMA!