- Lab
- Core Tech
![Labs Labs](/etc.clientlibs/ps/clientlibs/clientlib-site/resources/images/labs/lab-icon.png)
Guided: Portals and APIs in React
In this Guided Code Lab, you will create an interactive Movie Info Application using React. You'll learn key React concepts like components, state management, APIs, and portals while fetching and displaying movie data dynamically in a modal window. By the end, you'll have a fully functional movie listing app and practical experience in modern web development. Perfect for beginners or those looking to sharpen their React skills!
![Labs Labs](/etc.clientlibs/ps/clientlibs/clientlib-site/resources/images/labs/lab-icon.png)
Path Info
Table of Contents
-
Challenge
Introduction
In this Code Lab, you will build a Movie App that allows users to explore a variety of movies and view detailed information through a modal interface. Along the way you will learn to use React components, Portals, and hooks, efficiently manage state, and dynamically interact with APIs to fetch and display movie data.
Tasks can be validated by clicking on the validate buttons next to them. If you are stuck or would like to compare solutions, a
solution
directory has been provided for you as well.Application Features:
- Movie Listing: Display a comprehensive list of movies fetched from an API.
- Dynamic Modal Display: When a user clicks on a movie, a modal should appear with detailed information about the selected movie.
- Interactive User Interface: Ensure smooth interactions and a responsive design that enhances user experience.
How the Application Functions:
- The homepage displays a list of popular movies fetched from an API.
- Users can click on any movie title to open a modal with detailed information about that movie.
- The modal provides a user-friendly interface for exploring more about each movie without leaving the main page.
You Will Work Within the Following Files:
App.jsx
: Manages the overall application layout and logic for rendering componentsMovieList.jsx
: Handles fetching and displaying a list of movies with click interactionsMovieModal.jsx
: Manages fetching and displaying detailed information about a selected movie in a modal
Directory Structure:
src/components
App.jsx
: The main application component managing the layout and rendering logicMovieList.jsx
: Component responsible for fetching and displaying the list of moviesMovieModal.jsx
: Component for rendering a modal with detailed movie information
src/styles
App.css
: Styles for the main application layout and elementsMovieModal.css
: Styles specific to the movie modal interface
Server and Backend Details:
While this lab focuses on front-end development, it involves fetching data from a pre-configured API. The server-side details are abstracted, allowing you to focus on React development and user interaction.
Starting the Server:
You need to start the server by running the command below in the Terminal:
npm run dev -- --host
This will start the server along with API's on port 3000.
Head over to the Web Browser tab and use the Open in new browser tab icon to try out the application!
Server Code:
The server is built using Express.js, a popular web framework for Node.js. It uses middleware like
cors
to handle cross-origin requests, ensuring the front-end can safely interact with the backend without running into cross-origin issues.Exposed Server Endpoints
GET /api/movies
: Fetches the list of available moviesGET /api/movies/:id
: Retrieves detailed information about a specific movie based on its ID
Excited? Time to dive in and create an engaging movie exploration experience!
-
Challenge
Implement Movie List Fetching and Listener for Managing Click
First, you need to create a responsive movie list by fetching data from an API that has been made available to you, and handle user interactions in the user interface.
You will begin by defining a state variable to hold the movie list, this is going to be crucial for ensuring your component can respond to changes in data, such as fetching new movie information or updating existing data. This allows your application to maintain a responsive and interactive user interface. Now, you need to to fetch data from an API and display it within a React component. Fetching data is crucial for creating dynamic applications. For this, you will use the
fetch()
API, a modern and versatile way to make HTTP requests to servers from web browsers.fetch()
returns aPromise
that resolves to aResponse
object, representing the response to the request, which you can use to read the response data and status.Important React Concepts
-
useEffect
Hook: This allows you to perform side effects in function components, such as data fetching, subscriptions, or manually changing the DOM. It is typically used to initiate fetch operations when the component mounts, ensuring that the data is retrieved and processed at the correct time. -
await
Keyword: This pauses the execution of an asynchronous function until aPromise
is resolved. It makes asynchronous code more readable and maintains the flow of synchronous code. -
useState
Hook: This manages state within functional components, enabling you to store and update data that changes over time, such as a list of movies fetched from an API. -
Error Handling: This is essential in data fetching operations. Use a
catch
block to handle any errors that occur during the fetch process, such as network issues or server errors. Logging errors to the console helps diagnose and resolve issues effectively.
Data Fetching Example
useEffect(() => { async function fetchData() { try { const response = await fetch('/api/data'); const sampleData = await response.json(); setData(sampleData); } catch (error) { console.error('Error fetching data:', error); } } fetchData(); }, []);
This snippet demonstrates how to fetch data using
fetch()
andawait
, update the component state with the retrieved data, and handle potential errors gracefully. Next, you need to render the list of movies using React's JSX syntax. Rendering lists in React involves iterating over an array of data and returning JSX elements for each item, which is a common pattern for displaying dynamic content.Remember:
-
JSX allows you to write HTML-like syntax in JavaScript, which is transformed into React elements. When rendering a list, you can map over an array of data and return a JSX element for each item.
-
When rendering lists, each element should have a unique
key
prop to help React identify which items have changed, been added, or been removed. This improves performance and avoids issues with the rendering process. -
Use JavaScript's
map()
method to iterate over the array of movies and return a list of JSX<li>
elements. Each<li>
should contain the movie's title and director. -
You can handle click events by attaching an
onClick
event handler to elements. This enables interaction and communication between components.
Here's an example as to how you would normally render an array of objects representing books, showcase their titles and authors, and handle clicks to notify the parent component about the selected book.
<ul> {books.map(book => ( <li key={book.id} onClick={() => onBookClick(book.id)}> {book.title} by {book.author} </li> ))} </ul>
You need to manage the selected movie ID. This is crucial because it allows for dynamic interaction within the application. By keeping track of the selected movie, the UI can be updated to show a modal with specific details or perform actions based on the user's choice. Such dynamic interaction is essential for creating a responsive and engaging user experience. Once you have state in place, you need to implement an event listener in the
App
component to handle user interactions with the movie list. This involves capturing the movie ID when a user clicks on a movie and updating the application state. Next, you will render theMovieList
component in theApp
component and pass an event listener to manage user clicks. This integration is essential for facilitating communication between components and ensuring the UI updates dynamically in response to user interactions. Well done! Head over to the Web Browser tab and use the Open in new browser tab icon to try out the application! You will see the movies being fetched and displayed as a list. -
-
Challenge
Implement Movie Details Fetching and Modal
You'll now be focusing on implementing and integrating the
MovieModal
component to enhance the user experience by displaying detailed information about each movie when it is selected. This step involves utilizing React Portals to create a modal that overlays the application interface, allowing users to view additional details without navigating away from the main page.What is
ReactDOM.createPortal
?ReactDOM.createPortal
is a tool in React that lets you display a component outside of its normal parent. This is helpful for things like modals, tooltips, or dropdown menus, where you want the component to appear outside of the usual layout without affecting the parent component's style. By usingcreatePortal
, you can place elements in a specific spot in the DOM, making it easier to manage their appearance and behavior on the page.To create a portal, use the following syntax:
ReactDOM.createPortal( children, // The JSX content to render container // A DOM element where the children will be rendered )
- children: This is the content you want to render in the portal. It can be any valid JSX or React component.
- container: This is the DOM node where the content will be rendered. It should be a direct reference to a DOM element, typically obtained via
document.getElementById
. Now that you have the containers set up in theMovieModal
component, it's time to display the movie details such as the title, director, and description. Now, you need to to fetch movie details from an API. Fetching data is crucial for creating dynamic applications. For this, you will usefetch()
API, a modern and versatile way to make HTTP requests to servers from web browsers.fetch()
returns aPromise
that resolves to aResponse
object, representing the response to the request, which you can use to read the response data and status.
-
Challenge
Display Movie Modal and Handle Modal Closure
It's time to focus on handling the closure of the modal. By resetting the selected movie ID the application will hide the modal, providing users with a clear and intuitive experience. You will do this by setting the
selectedMovieId
state tonull
. You now need to render theMovieModal
component in theApp.jsx
file. You already have access to theselectedMovieId
, and theMovieModal
should only be rendered whenselectedMovieId
exists. This ensures that the modal is displayed dynamically based on the user's interaction with the movie list. For this, you can make use of conditional rendering using&&
operator. This way, you guarantee that the modal appears only when a specific movie is selected, thereby creating a more interactive and responsive user experience. Awesome! Head over to the Web Browser tab and use the Open in new browser tab icon to try out the application! Currently, the modal displays when a movie is selected from the list, but there is no way to close it. Adding a button to close the modal is essential for providing a smooth and intuitive user experience. You are done! Head over to the Web Browser tab and use the Open in new browser tab icon to try out the application! See the movies being fetched. Click on any movie to see the movie information. Once the information is displayed, select Close at top to close the movie information.
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the author’s guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.