Exercise: React Lifecycle Methods
#
ObjectiveYour 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 StartedThis is part 3 of TrueCoders' React Exercise Series.
We'll be in the same react repository that you worked in for part 2.
#
StepsReact 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 ComponentCreate a new class component.
- Create a new file called
filmsList.jsx
in yourcomponents/
folder - Import and destructure the
Component
from thereact
package - Add a class called
FilmsList
that renders an empty unordered list - You should have:
#
Exercise 2: Films StateCreate state to manage the list of Studio Ghibli films.
- Create a constructor for the
FilmsList
class - Define a
list
property onthis.state
that is assigned an empty array
#
Exercise 3: Method to Get FilmsCreate a method to retrieve the list of films.
- Create a method called
getFilms
on theFilmsList
class - The method should call the
fetch
function with the following url parameter: https://ghibliapi.herokuapp.com/films - Call the
then
method on the returned promise- the first
then
call should receive a callback function that returns the result parsed to json
- the first
- Make another
then
call on the returned promise- the second
then
call should receive a callback function that usesthis.setState()
to setthis.state.list
equal to the result
- the second
- Lastly add a
catch
method call that should receive a callback function that will handle an error if one occurs
#
Exercise 4: Fetch FilmsCall getFilms()
once the component mounts.
- Create a
componentDidMount
method on theFilmsList
class - Call
getFilms
within the method body
#
Exercise 4: Render the Films ListRender the list to the DOM.
- In the
render
method, update the content of theul
element to be a JSX expression that calls themap
method onthis.state.list
- Pass a callback function to the
map
method that returns ali
element for each film inthis.state.list
- Add the film's title as the text content of the
li
- Add a
key
prop to theli
that 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 ComponentRender the FilmsList
component in App
.
- Import the
FilmsList
component from./components/FilmsList
- In the
render
method of theApp
class, render theFilmsList
component below theul
from the previous lesson
#
Helpful LinksIf you feel stuck, or would like to see the finished code for this exercise to check your work, check out: