1. Code
  2. JavaScript
  3. React

React Crash Course for Beginners, Part 3

Scroll to top
12 min read
This post is part of a series called React Crash Course for Beginners.
React Crash Course for Beginners, Part 4

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 <Movie /> component that will display information about an individual movie.

Adding a Movie Component

The <Movie /> component will display information about an individual movie. Multiple <Movie /> 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 <Movie /> 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:

1
.App {
2
  text-align: center;
3
}
4
5
.App-logo {
6
  animation: App-logo-spin infinite 20s linear;
7
  height: 80px;
8
}
9
10
.App-header {
11
  background-color: steelblue;
12
  height: 70px;
13
  padding: 20px;
14
  color: white;
15
}
16
17
.App-intro {
18
  font-size: large;
19
}
20
21
/* new css for movie component */
22
* {
23
  box-sizing: border-box;
24
}
25
26
.movies {
27
  display: flex;
28
  flex-wrap: wrap;
29
}
30
31
.App-header h2 {
32
  margin: 0;
33
}
34
35
.add-movies {
36
  text-align: center;
37
}
38
39
.add-movies button {
40
  font-size: 16px;
41
  padding: 8px;
42
  margin: 0 10px 30px 10px;
43
}
44
45
.movie {
46
  padding: 5px 25px 10px 25px;
47
  max-width: 25%;
48
}

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 <Movie /> component. Inside the /src/components/ folder, create a new Movie.js file, open it in an editor, and add the following:

1
import React, { Component } from 'react';
2
3
class Movie extends Component {
4
  render() {
5
    return (
6
      <div className="movie">
7
        <h2>{ this.props.title }</h2>

8
      <div><img width="200" src={ this.props.poster } /></div>
9
        <p>({ this.props.year })</p>

10
        <p>{ this.props.description }</p>

11
      </div>

12
    );
13
  }
14
}
15
16
export default Movie;

This is pretty similar to the <Header /> component except we're referencing several props rather than just the one. Let's use our <Movie /> component to display some movies.

In App.js add four <Movie /> components inside a <div> wrapper so we can easily apply styles to just the movie elements. Here is the full App.js code:

1
import React, { Component } from 'react';
2
import '../App.css';
3
import Header from './Header';
4
import Movie from './Movie';
5
6
class App extends Component {
7
  render() {
8
    return (
9
      <div className="App">
10
        <Header text="Discover Your Movie Mojo!" />
11
        <p className="App-intro">Sharing a few of our favourite movies</p>

12
        <div className="movies">
13
          <Movie 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" />
14
          <Movie 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" />
15
          <Movie 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" />
16
          <Movie 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" />
17
        </div>

18
      </div>

19
    );
20
  }
21
}
22
23
export default App;

Note how we explicitly import the <Movie /> component, just like we did for <Header />, to make it available in the code. Each movie component implements props for title, year, description, and poster.

The result is four <Movie /> components added to our gallery.

Manually adding Movie componentsManually adding Movie componentsManually 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:

1
// some sample movies

2
const initialMovies = {
3
  movie1: {
4
    title: "Ferris Bueller's Day Off",
5
    year: "1986",
6
    description: "A high school wise guy is determined to have a day off from school, despite what the principal thinks of that.",
7
    poster: "./posters/ferris.png"
8
  },
9
  movie2: {
10
    title: "Bridget Jones' Diary",
11
    year: "2001",
12
    description: "A British woman is determined to improve herself while she looks for love in a year in which she keeps a personal diary.",
13
    poster: "./posters/bridget-jones.png"
14
  },
15
  movie3: {
16
    title: "50 First Dates",
17
    year: "2004",
18
    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.",
19
    poster: "./posters/50-first-dates.png"
20
  },
21
  movie4: {
22
    title: "Matilda",
23
    year: "1996",
24
    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.",
25
    poster: "./posters/matilda.png"
26
  }
27
};
28
29
const additionalMovies = {
30
  movie5: {
31
    title: "Dirty Dancing",
32
    year: "1987",
33
    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.",
34
    poster: "./posters/dirty-dancing.png"
35
  },
36
  movie6: {
37
    title: "When Harry Met Sally",
38
    year: "1989",
39
    description: "Harry and Sally have known each other for years, and are very good friends, but they fear sex would ruin the friendship.",
40
    poster: "./posters/when-harry-met-sally.png"
41
  },
42
  movie7: {
43
    title: "Elf",
44
    year: "2003",
45
    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.",
46
    poster: "./posters/elf.png"
47
  },
48
  movie8: {
49
    title: "Grease",
50
    year: "1978",
51
    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?",
52
    poster: "./posters/grease.png"
53
  }
54
};
55
56
export {initialMovies};
57
export {additionalMovies};

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

1
import {initialMovies} from '../movies';
2
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 <App />, 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 <App /> component class:

1
constructor() {
2
  super();
3
4
  this.state = {
5
    movies: {}
6
  };
7
}

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 <App /> component.

Adding empty stateAdding empty stateAdding 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.

1
constructor() {
2
  super();
3
4
  this.state = {
5
    movies: initialMovies
6
  };
7
}

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 <Movie /> components we added earlier.

Adding movies to our initial stateAdding movies to our initial stateAdding 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 <Movie /> components, and replace them with:

1
{
2
  Object
3
    .keys(this.state.movies)
4
    .map(key => <Movie key={key} meta={this.state.movies[key]} />)

5
}

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 <Movie /> component is outputted for each movie in the movies state object.

There are a couple of changes from the previous way we added a <Movie />, 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:

1
<div className="movie">
2
  <h2>{ this.props.meta.title }</h2>

3
  <div><img width="200" src={ this.props.meta.poster } /></div>
4
  <p>({ this.props.meta.year })</p>

5
  <p>{ this.props.meta.description }</p>

6
</div>
Movies initialized via stateMovies initialized via stateMovies 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 <App /> 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.

1
<div className="add-movies"><button onClick={this.loadAdditionalMovies}>Load more...</button></div>

When the button is clicked, a class method loadAdditionalMovies is called. Add this method to the <App /> component class:

1
loadAdditionalMovies() {
2
  var currentMovies = { ...this.state.movies };
3
  var newMovies = Object.assign( currentMovies, additionalMovies );
4
5
  this.setState({ movies: newMovies });
6
}

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:

1
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.

Loading more movies via updating stateLoading more movies via updating stateLoading 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!

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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.