So far in this React series, we’ve created a working sample app as a starting point for our ‘Movie Mojo’ gallery app, and we’ve seen how using props allows us to customize the appearance of components by passing in data rather than hard coding it.
In part three we’ll create our first custom component, and then add state to our app. This will allow us to easily manage the app data without being concerned about manually updating the DOM. Instead we’ll see how to let React handle all of the DOM rendering from now on.
A set of four movies will be displayed in our gallery on page load, and a further four will be loaded and displayed when the Load more… button is clicked.
Let’s first tackle adding the
component that will display information about an individual movie.
Adding a Movie Component
The
component will display information about an individual movie. Multiple
components will be displayed together to form a movie gallery of some feel-good movies. Hence the name of our React app, ‘Movie Mojo”!
Before we add the
component, let’s update the CSS in App.js
to style individual movies in the gallery. Open up App.css
and replace the styles with:
.App { text-align: center; } .App-logo { animation: App-logo-spin infinite 20s linear; height: 80px; } .App-header { background-color: steelblue; height: 70px; padding: 20px; color: white; } .App-intro { font-size: large; } /* new css for movie component */ * { box-sizing: border-box; } .movies { display: flex; flex-wrap: wrap; } .App-header h2 { margin: 0; } .add-movies { text-align: center; } .add-movies button { font-size: 16px; padding: 8px; margin: 0 10px 30px 10px; } .movie { padding: 5px 25px 10px 25px; max-width: 25%; }
This styles the gallery to display movies in a grid formation and improve spacing around other visual elements.
Also, in /public/posters/
, I’ve added 12 movie posters for convenience that you can use in your own project, if you’re following along. You can download them as part of the finished project for part 4. Simply copy across the posters
folder to your own React app public
folder.
You can also download your own movie posters from the original website. For this tutorial, I used cinematerial.com for all the movie posters. There is a small fee to download the posters, but there are probably many other sources for posters if you want to try elsewhere.
OK, back to our
component. Inside the /src/components/
folder, create a new Movie.js
file, open it in an editor, and add the following:
import React, { Component } from 'react'; class Movie extends Component { render() { return (); } } export default Movie;{ this.props.title }
({ this.props.year })
{ this.props.description }
This is pretty similar to the
component except we’re referencing several props rather than just the one. Let’s use our
component to display some movies.
In App.js
add four
components inside a
App.js
code:
import React, { Component } from 'react'; import '../App.css'; import Header from './Header'; import Movie from './Movie'; class App extends Component { render() { return (); } } export default App;Sharing a few of our favourite movies
Note how we explicitly import the
component, just like we did for
, to make it available in the code. Each movie component implements props for title
, year
, description
, and poster
.
The result is four
components added to our gallery.
It’s very tedious to add movies manually one at a time in App.js
. In practice, app data would likely come from a database and be temporarily stored in a JSON object before being added to the state object in your app.
Managing React State
What is state in a React app? You can think of it as a single JavaScript object which represents all the data in your app. State can be defined on any component, but if you want to share state between components then it’s better to define it on the top-level component. State can then be passed down to child components and accessed as required.
Even though state is one main object, that object can contain multiple sub-objects related to different parts of your app. For example, in a shopping cart app, you might have a state object for the items in your order, and another object for monitoring inventory.
In our ‘Movie Mojo’ app, we have just a single sub-state object to store the movies in our gallery.
The core idea behind using state is that whenever data in your app changes, React updates the relevant parts of the DOM for you. All you have to do is manage the data, or state, in your app, and React handles all the DOM updates.
Adding Movies via State
For the sake of simplicity, we’ll forgo the database step and pretend our movie data has been retrieved from a database and stored in JSON format.
To demonstrate adding items to an initial state, as well as updating state when an event occurs (such as a button press), we’ll use two JSON objects, each containing data about four movies.
In the src
folder, add a new movies.js
file, open it in an editor, and add the following code to define our two JSON objects:
// some sample movies const initialMovies = { movie1: { title: "Ferris Bueller's Day Off", year: "1986", description: "A high school wise guy is determined to have a day off from school, despite what the principal thinks of that.", poster: "./posters/ferris.png" }, movie2: { title: "Bridget Jones' Diary", year: "2001", description: "A British woman is determined to improve herself while she looks for love in a year in which she keeps a personal diary.", poster: "./posters/bridget-jones.png" }, movie3: { title: "50 First Dates", year: "2004", description: "Henry Roth is a man afraid of commitment up until he meets the beautiful Lucy. They hit it off and Henry think he's finally found the girl of his dreams.", poster: "./posters/50-first-dates.png" }, movie4: { title: "Matilda", year: "1996", description: "Story of a wonderful little girl, who happens to be a genius, and her wonderful teacher vs. the worst parents ever and the worst school principal imaginable.", poster: "./posters/matilda.png" } }; const additionalMovies = { movie5: { title: "Dirty Dancing", year: "1987", description: "Spending the summer at a Catskills resort with her family, Frances 'Baby' Houseman falls in love with the camp's dance instructor, Johnny Castle.", poster: "./posters/dirty-dancing.png" }, movie6: { title: "When Harry Met Sally", year: "1989", description: "Harry and Sally have known each other for years, and are very good friends, but they fear sex would ruin the friendship.", poster: "./posters/when-harry-met-sally.png" }, movie7: { title: "Elf", year: "2003", description: "After inadvertently wreaking havoc on the elf community due to his ungainly size, a man raised as an elf at the North Pole is sent to the U.S. in search of his true identity.", poster: "./posters/elf.png" }, movie8: { title: "Grease", year: "1978", description: "Good girl Sandy and greaser Danny fell in love over the summer. When they unexpectedly discover they're now in the same high school, will they be able to rekindle their romance?", poster: "./posters/grease.png" } }; export {initialMovies}; export {additionalMovies};
Before we can reference the JSON objects in our
component, we need to import them. Add this to the top of App.js
:
import {initialMovies} from '../movies'; import {additionalMovies} from '../movies';
Each JSON object is now available via the variables initialMovies
and additionalMovies
. So far, though, we don’t have any state associated with our app. Let’s fix that now.
The top-level component in our ‘Movie Mojo’ app is
, so let’s add our state object here. We need state to be initialized along with the component class, which we can do via the constructor function.
When using a constructor function in a React class, you need to call super()
first as the Component
object we’re extending needs to be initialized before anything else. Plus, the this
keyword will not be available inside the constructor until after super()
has returned.
To initialize our state
object, add this inside the
component class:
constructor() { super(); this.state = { movies: {} }; }
This will create an empty state object for our React app. Using the React developer tools, we can see the state
object initialized directly on the
component.
However, we want to initialize the state
object with some movies so they display straight away on page load. To do this, we can initialize the movies
state object with initialMovies
instead of an empty object.
constructor() { super(); this.state = { movies: initialMovies }; }
This will set the initial state for our app to the four movies stored in the initialMovies
JSON object, but the movies in the gallery are still being displayed via the hard-coded
components we added earlier.
We need to output the movies in the movie
state object instead, which we can do by using a loop to iterate over each movie.
Start by removing the hard-coded
components, and replace them with:
{ Object .keys(this.state.movies) .map(key =>) }
This code requires some explanation. The movie
state object contains individual movies stored as objects, but to iterate over them it would be easier to work with an array instead.
So we use Object.keys()
to grab all the keys for the movie objects and store them in an array. This is then iterated over using .map()
, and a
component is outputted for each movie in the movies
state object.
There are a couple of changes from the previous way we added a
, though. Firstly, we pass in all the information for an individual movie via a single meta
prop. This is actually more convenient than before, where we specified a separate prop for each movie attribute.
Also, notice that we specify a key
prop too. This is used internally by React to keep track of components that have been added by the loop. It’s not actually available to be used by the component, so you shouldn’t try to access it in your own code.
Without a key
prop, React throws an error, so it’s important to include it. React needs to know which new movies have been added, updated, or removed so it can keep everything synchronized.
We need to do one more thing before our components can be displayed. Open up Movie.js
, and for each reference to a prop, prefix it with meta
, as follows:
{ this.props.meta.title }
({ this.props.meta.year })
{ this.props.meta.description }
Loading More Movies
We’ve seen how to display movies that have been added to state as our app initializes, but what if we wanted to update our movie gallery at some point?
This is where React really shines. All we have to do is update the movies in the movie
state object, and React will automatically update all parts of our app that use this object. So, if we add some movies, React will trigger the
component’s render()
method to update our movie gallery.
Let’s see how we can implement this.
Start by adding an HTML button inside the closing div wrapper in App.js
.
When the button is clicked, a class method loadAdditionalMovies
is called. Add this method to the
component class:
loadAdditionalMovies() { var currentMovies = { ...this.state.movies }; var newMovies = Object.assign( currentMovies, additionalMovies ); this.setState({ movies: newMovies }); }
Updating state is relatively simple as long as you follow the recommended method, which is to copy the current state object to a new object, and update that copy with new items. Then, to set the new state, we call this.setState
and pass in our new state object to overwrite the previous one. As soon as the state is updated, React updates only the parts of the DOM that have been affected by the change to state.
The first line in loadAdditionalMovies()
uses a spread
operator to copy all properties of the this.state.movies
object into the new currentMovies
object.
After that, we use Object.assign
to merge two objects together, resulting in the list of new movies being added to the current list.
There is just one more step we need to complete before the loadAdditionalMovies()
method will work. To reference any custom component method, we first need to manually bind it to the component class.
This is a quirk of React and is just something you’ll have to remember to do. Any time a method is accessed without having been manually bound, React will complain and throw a compilation error.
Add this to the class constructor in App.js
:
this.loadAdditionalMovies = this.loadAdditionalMovies.bind(this);
As long as you remember to use this workaround for every custom method that requires the use of this
, you won’t run into any problems.
Now, try clicking the Load more… Button. You should see four more movies added to the gallery.
This demonstrates a key strength of React. That is, letting you focus on the data in your app and leave all the mundane updating of the DOM to React. To add movies, all we had to do was to update the data in our movie
state object, and React took care of everything else.
Our example app is still pretty basic, but imagine a much more complex app with many components and multiple state objects. Trying to manually update the DOM as the data in your app changes would be a huge (and error-prone) task!
Conclusion
In this tutorial, we really made some progress with our ‘Movie Mojo’ app. We used React state to help manage the list of movies in our app. Not only did we add movies to the initial state object as our app initialized, but we also updated the list of movies in our gallery when the Load more… Button was clicked.
In part four, and the last tutorial in this series, we’ll take a look at how we can manually add a movie to our gallery via a custom form. Users will be able to fill out the form and add details about a movie, which will be added to the list of movies displayed in the gallery.
Powered by WPeMatico