Exercise: React Lifecycle Methods
Objective#
Your objective is to create a Films component that will fetch a list of films from the Studio Ghibli API, and display them to the screen as a rendered list.
Getting Started#
This is part 3 of TrueCoders' React Exercise Series.
We'll be in the same react repository that you worked in for part 2.
Steps#
React Series Part 3 has multiple exercises
- Exercise 1: FilmsList Component
- Exercise 2: Films State
- Exercise 3: Method to Get Films
- Exercise 4: Fetch Films
- Exercise 5: Render FilmsList Component
Exercise 1: FilmsList Component#
Create a new class component.
- Create a new file called
filmsList.jsxin yourcomponents/folder - Import and destructure the
Componentfrom thereactpackage - Add a class called
FilmsListthat renders an empty unordered list - You should have:
Exercise 2: Films State#
Create state to manage the list of Studio Ghibli films.
- Create a constructor for the
FilmsListclass - Define a
listproperty onthis.statethat is assigned an empty array
Exercise 3: Method to Get Films#
Create a method to retrieve the list of films.
- Create a method called
getFilmson theFilmsListclass - The method should call the
fetchfunction with the following url parameter: https://ghibliapi.herokuapp.com/films - Call the
thenmethod on the returned promise- the first
thencall should receive a callback function that returns the result parsed to json
- the first
- Make another
thencall on the returned promise- the second
thencall should receive a callback function that usesthis.setState()to setthis.state.listequal to the result
- the second
- Lastly add a
catchmethod call that should receive a callback function that will handle an error if one occurs
Exercise 4: Fetch Films#
Call getFilms() once the component mounts.
- Create a
componentDidMountmethod on theFilmsListclass - Call
getFilmswithin the method body
Exercise 4: Render the Films List#
Render the list to the DOM.
- In the
rendermethod, update the content of theulelement to be a JSX expression that calls themapmethod onthis.state.list - Pass a callback function to the
mapmethod that returns alielement for each film inthis.state.list - Add the film's title as the text content of the
li - Add a
keyprop to thelithat is set to the film'sid
Feel free to add more content from each film to the list item's inner html.
Exercise 5: Render FilmsList Component#
Render the FilmsList component in App.
- Import the
FilmsListcomponent from./components/FilmsList - In the
rendermethod of theAppclass, render theFilmsListcomponent below theulfrom the previous lesson
Helpful Links#
If you feel stuck, or would like to see the finished code for this exercise to check your work, check out: