Movie Card
So by now you should have a pretty good idea on how to build simple components and make them available so they can be reused throughout a website. Now let's build a more complex component in which we will reuse previously built components. The Card component is widely used to display individual movies as well as the large Featured Movie at the top of the homepage and in individual pages.
In this component we will reused the Eyebrow, Button and other small components to build a larger component. This is the Atomic Design approach where you first build Atoms and then build Molecules, Organisms, etc. The Card component is a Molecule because it combines multiple Atoms.
Building the Movie Card Component
The Movie card component has a lot of moving pieces and to understand it better we are going to build it incrementally.
Importing all resources:
Inside the Components folder create a new folder called Card
Inside the Card folder create a new
index.js
fileInside index.js add the following code:
We're starting by importing all the dependencies we will need for this component. First we import all React and Gatsby-native resources like
{ Link }
,PropTypes
,Image
, and of course,React
itself.Then we import previously built components: Rating, Stars, and Heading
To style the Card we import
styles.modules.scss
which you will create shortlyAnd finally, we import
customPropTypes
which is a list of PropTypes we have written to make them reusable in any component
Building the Card Component:
Just below the last import, let's create a new JavaScript function which will use the name of our Component
Let's add a few props we expect the Card to use
And make it reusable by adding
export default Card;
The Card function expects several props including title, path, image, subtitle, rating, and stars. These props are basically the fields that make up the card.
The
return
statement will provide us with the markup and structure we expect when rendering a card on the browser. Let's handle that markup now.
Writing the expected markup:
Modify the Card function as shown below
The rest of the code above is pretty self-explanatory. We are wrapping the remaining fields in specific markup with unique CSS classes.
Define the Card's PropTypes:
After
export default Card;
, add the following block of code to define the PropTypes for the card:
As we indicated before, JavaScript is a loosely-typed language but Gatsby/React requires for Props to have a defined type. Most props above are using built-in propTypes found in
prop-types
, which was imported asPropTypes
. However, for the Image field, we wrote a custom propType which we are importing as{ fluidImage }
That's it! The Card Component is done.
See the full component code below
Next, we are going to make use of the Card component to build the movie listings.
Last updated
Was this helpful?