React Crash Course for Beginners, Part 3

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:

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 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:

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

 wrapper so we can easily apply styles to just the movie elements. Here is the full App.js code:

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.

Manually adding Movie components

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:

Before we can reference the JSON objects in our  component, we need to import them. Add this to the top of App.js:

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:

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.

Adding empty state

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.

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.

Adding movies to our initial state

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:

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:

Movies initialized via state

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:

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:

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.

Loading more movies via updating state

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!


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

Leave a Comment

Scroll to Top