📂
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
  • Rendering Search Results
  • Passing imdbIDs to ShowMovie
  • Rendering Movie Details

Was this helpful?

  1. Archived Section
  2. (Archived) ReactJS
  3. React Router

OMDB Search

Now to get the search feature working. We'll need a couple functions in order to correctly search for a movie.

  • searchChange, to update the value of the input field

  • search, to take the searchTerm and query OMDB

Let's make these changes in src/components/OMDBSearch.jsx

import React, { Component } from 'react';
import Navbar from './Navbar';
import MovieResult from './MovieResult';

class OMDBSearch extends Component {
  constructor() {
    super();
    this.state = {
      searchTerm: '',
      results: []
    };
  }
  searchChange (e) {
    this.setState({searchTerm: e.target.value});
  }
  search (e) {
    console.log("searching");
    e.preventDefault();
    fetch(`http://omdbapi.com/?s=${this.state.searchTerm}`)
      .then(response => {
        response.json().then(data => {
          console.log(data.Search);
          this.setState({results: data.Search});
        });
      }).catch(error => {
        this.setState({results: null});
      });
  }
  render () {
    return (
      <div>
        <Navbar />
        <h1>Search for Movies</h1>
        <form onSubmit={(e) => this.search(e)}>
          <input type="text"
                 value={this.state.searchTerm}
                 onChange={(e) => this.searchChange(e)} />
          <input type="submit" />
        </form>
        {this.results()}
      </div>
    );
  }

  results() {
    return this.state.results.map(result =>
      <MovieResult title={result.Title}
                   year={result.Year}
                   poster={result.Poster}
                   imdbID={result.imdbID} />
    );
  }
}

module.exports = OMDBSearch;

Much of this is similar to the Todo app from before, but what's with this fetch function. Where did it come from?

fetch is a new and experimental interface for interacting with network resources. It's similar to AJAX, only it's available natively in some browsers. Note that this will only work in later versions of Chrome and Firefox, but there are scripts called polyfills that allow you to use this feature in all browsers.

After testing the code above, there should be search results appearing in the console. Now for rendering...

Rendering Search Results

To make things simpler, we're going to render the search results directly in the OMDBSearch component, without making a separate component. Let's modify the render function to do this.

render () {
  const results = this.state.results.map((movie, idx) => {
    return (
      <div className="well" key={idx}>
        <h2>{movie.Title}</h2>
        <p>imdbID: {movie.imdbID}</p>
      </div>
    );
  });

  return (
    <div>
      <h1>Search for Movies</h1>
      <form onSubmit={this.search}>
        <input type="text"
               value={this.state.searchTerm}
               onChange={this.searchChange} />
        <input type="submit" />
      </form>
      <div>{results}</div>
    </div>
  );
}

Passing imdbIDs to ShowMovie

To link correctly to the ShowMovie components, we'll need a react-router module called Link in order to create the links. In /src/components/OMDBSearch.jsx, let's require the Link module.

const Link = require('react-router').Link;

Then, we'll create the Link components inside of the render function. This will allow us to create links and pass the imdbIDs to the ShowMovie component.

render () {
  const results = this.state.results.map((movie, idx) => {
    return (
      <div className="well" key={idx}>
        <h2><Link to={`/results/${movie.imdbID}`} >{movie.Title}</Link></h2>
      </div>
    );
  });

  return (
    <div>
      <h1>Search for Movies</h1>
      <form onSubmit={this.search}>
        <input type="text"
               value={this.state.searchTerm}
               onChange={this.searchChange} />
        <input type="submit" />
      </form>
      <div>{results}</div>
    </div>
  );
}

Test the app again by searching for a movie and clicking on one of the links. We should be redirected to the ShowMovie component, where the imdbID is rendered to the page.

Rendering Movie Details

In order to render movie details, we'll need to fetch the data in a similar manner as OMDBSearch. Our workflow will look like so:

  • Set the initial state of the movie to null while we search for the movie

    • If the movie doesn't exist, display Loading to the page

  • Search for the movie using the imdbID passed via route params

    • Once the data is found, set the movie state

  • Render the movie to the page

In MovieShow, let's add the following:

import React, { Component } from 'react';
import Navbar from './Navbar'

class ShowMovie extends Component {
  constructor(props) {
    super(props);

    this.state = {
      movie: null
    }

    fetch(`http://omdbapi.com/?i=${this.props.params.imdbID}`)
    .then(response => {
      console.log("got response:", response);
      response.json().then(data => {
        this.setState({movie: data});
      });
    }).catch(error => {
      console.log("error");
      this.setState({movie: null});
    });
  }

  render() {
    const movie = this.state.movie;
    if (!movie) {
      return <div>
        <Navbar />
        <h2>Loading...</h2>
      </div>
    }

    return (
      <div>
        <Navbar />
        <h2>({movie.Year}) {movie.Title}</h2>
        <img src={movie.Poster} />
        <p>
          {movie.Plot}
        </p>
      </div>
    );
  }
}

export default ShowMovie;

We should now have a working movie app, complete with a Back button via Link.

PreviousOMDB RouterNextAdditional Resources

Last updated 4 years ago

Was this helpful?

Documentation for fetch
window.fetch polyfill