📂
SEI 1019
  • Introduction
  • About These Notes
  • Syllabus
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Callbacks
      • Timing Functions
      • Iterators
    • DOM and Events
    • DOM Manipulation
    • HTML5 Canvas
    • How To Reduce Redundancy
    • (2019) JavaScript OOP
    • (2016) OOP with Classes
    • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Node/Express
    • Node
      • Intro to Node
      • Node Modules
      • Node Package Manager (NPM)
    • Express
      • Intro to Express
        • Routes
        • Views
        • Templates
        • Layouts and Controllers
        • CRUD & REST
          • Get and Post
          • Put and Delete
      • APIs with Express (request)
      • APIs with Express (axios)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Mood Points
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Intro to WDI (Course Info)
    • Being Successful in WDI
    • Internet Fundamentals
      • Internet Lab
    • User Stories and Wireframing
      • Wireframing Exercise: Build an Idea
    • Post WDI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Setup
  • Create A Simple Movie Component
  • Viewing the Component
  • Dealing with Errors
  • Passing Information via Properties
  • Reusing the Component
  • Solution
  • Reflecting on Reusability
  • Internet Dive Point

Was this helpful?

  1. React (Updated 2019)
  2. Intro to React

Lab: LotR

PreviousNested ComponentsNextReact State

Last updated 4 years ago

Was this helpful?

Let's build something small to reinforce what you've learned so far. We're going to practice creating components and passing information into them.

We'll build a simple website that shows title and runtime information about the original Lord of the Rings Trilogy.

Specifically, at the end of this lesson, your solution will look like this:

Setup

Create a new react app called lord-of-the-rings:

npx create-react-app lord-of-the-rings
cd lord-of-the-rings
npm start

Um, excuse me, you made a typo

Nope! The command npx is a legitimate thing. It's called a package runner. You can read more about it . It enables you to run the command create-react-app without globally installing create-react-app.

Note: If you globally installed create-react-app, you don't need the npx portion of the above command.

Create A Simple Movie Component

Open up your ./src directory in your favorite text editor.

Inside of ./src folder, create a new React Component file called Movie.js.

src/Movie.js

import React, { Component } from 'react';

class Movie extends Component {
  render() {
    return (
      // we'll add JSX here
    )
  }
}

export default Movie

or, we could write it as a functional component, like so:

import React from 'react'

const Movie = () => {
   return (
     // code goes here!
   )
}

export default Movie

Let's add some JSX to the render function so this component will be visible in our application. Let's keep the JSX simple for now, and we'll make it more complex once we're sure it works.

Remember, our goal is to display the movie title and runtime information.

Let's add one <h1> for the movie title, and a <p> for the runtime. Remember, the JSX of each component in React ultimately must descend from just one parent element. Wrap the <h1> and <p> in a <div>.

The JSX will look like this:

<div>
  <h1>The Lord of the Rings: A Trilogy</h1>
  <p>4h 37min</p>
</div>

Add this JSX to the component so that it's returned from the render() method.

src/Movie.js

import React, { Component } from 'react';

class Movie extends Component {
  render() {
    return (
      <div>
        <h1>The Lord of the Rings: A Trilogy</h1>
        <p>4h 37min</p>
      </div>
    )
  }
}

export default Movie

so what does it look like as a functional component? I'm so glad you asked!

import React from 'react'

const Movie = () => {
   return (
      <div>
         <h1>The Lord of the Rings: A Trilogy</h1>
         <p>4h 37min</p>
      </div>
   )
}

export default Movie

Viewing the Component

Let's make this component appear on the page. One great thing about using create-react-app is it tells us exactly what we need to do to start editing our application. The homepage says, "To get started, edit src/App.js and save to reload." Let's do that!

Open src/App.js.

Add our <Movie /> component just after the paragraph. Go back to the app and see if it appears.

Dealing with Errors

Uh oh. There's an error.

Failed to compile
./src/App.js
  Line 15:  'Movie' is not defined  react/jsx-no-undef

'Movie' is not defined? Ah.

One does not simply refer to components in React. In our src/App.js, we're saying "Display what's returned from the Movie component." However - we haven't told src/Apps.js where to find the Movie component! We must import a component before using it.

Add this import statement with the other imports at the top of the src/App.js file.

import Movie from './Movie';

Now you should see the page without the error message, and it should have the JSX from the Movie component.

The entire App.js should look like this:

src/App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Movie from './Movie';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <Movie />
        </header>
      </div>
    );
  }
}

export default App;

or, if you're following along building a functional component, it will look like:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Movie from './Movie';

const App = () => {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <Movie />
        </header>
      </div>
    );
}

export default App;

Passing Information via Properties

We need to make our Movie component accept information so we can use it to display different titles and runtimes. In the src/App.js file, add title, hours, and minutes props to the <Movie> tag. We'll be able to read the value of these props from inside the component. You can name props pretty much anything you want - but it's good practice to be descriptive!

<Movie title="The Fellowship of the Ring" hours="2" minutes="58" />

We'll be able to read the value of these props from inside the component. You can name props pretty much anything you want - but it's good practice to be descriptive!

React gathers all of the props we added to the call to <Movie /> and makes them each available through the this.props object. This means that inside the Movie component, we can now access the values of props through this.props.title, this.props.hours and this.props.minutes. Remember, we use curly braces { } to display the value of something.

In src/Movie.js, change the <h1> to display the value of the title prop by writing {this.props.title}.

Note: in the event that you're using a functional component, you can omit the word "this" from these notes! Just remember to pass props into your function, like so:

const Movie = (props) => {

There was also the hours and minutes props. Update the JSX to access and display the value of each prop we created.

The render() function ends up looking like this:

src/Movie.js

import React, { Component } from 'react';

class Movie extends Component {
    render() {
        return(
            <div>
                <h1>The Lord of the Rings: {this.props.title}</h1>
                <p>{this.props.hours}h {this.props.minutes}min</p>
            </div>
        )
    }
}

export default Movie;

or, as functional:

import React from 'react'

const Movie = (props) => {
  return(
    <div>
      <h1>The Lord of the Rings: {props.title}</h1>
      <p>{props.hours}h {props.minutes}min</p>
    </div>
  )
}

export default Movie

Refresh the page and make sure everything works correctly.

Reusing the Component

Once you've got props working for one component, then write two more!

In src/App.js, call the <Movie /> component again with different values for the title, hours and minutes properties. Display information for the complete trilogy! (If you don't know everything about Lord of the Rings off the top of your head, here it is).

<Movie title="The Fellowship of the Ring" hours="2" minutes="58" />
<Movie title="The Two Towers" hours="2" minutes="59" />
<Movie title="The Return of the King" hours="3" minutes="21" />

Solution

When you're finished, review the reflections below.

Reflecting on Reusability

Components are great because they allow us to compartmentalize code and easily reuse parts we create. We simply set the value of props and the component defines how everything should be displayed.

In this instance, we factored out some redundancy of the movie titles.

  • All these movies start with "Lord of the Rings:", so only the unique part is the prop.

  • Similarly, we don't have to rewrite the format of the runtime information.

Building and reusing components becomes especially powerful the more complex components become.

  • Imagine building a component for video search results inside YouTube.

    • The props list is huge:

      • ton of links

      • time information

      • preview images

      • options to add the result to a playlist

      • and all sorts of other things.

Building one component to rule all them all would save you a lot of time and headaches!

Internet Dive Point

In case you want to nerd out, here are handy links to the IMDB page for each movie:

Lord of the Rings: The Fellowship of the Ring
Lord of the Rings: The Two Towers
Lord of the Rings: The Return of the King
here on npmjs.com
Lord of the Rings movie info