Skip to main content

Updated for Fall 2026

In this workshop, we’ll be looking at doing frontend development with React. We use React to handle all of the dynamic behavior on the pages, so they actually do things when a user interacts with them. This is, of course, an essential element of web application development, because most users at this point expect web applications to be responsive to what they’re trying to do.

Background

React utilizes components to provide dynamic elements to web pages. Components return JSX, which may incorporate dynamic elements. The result of the dynamic execution is rendered by the browser.

You can learn more about React and it’s libraries. React also has a list of rules - patterns of how developers should work with React libraries.

For this module, we’ll explore the ListRecipes component and add edit functionality.

Setup

Let’s start with some process tasks.

Workshop Issue

Create an issue in GitHub associated with the task of completing the workshop. Here are the tasks you must complete as part of this workshop:

  • Update title of React app
  • Update App.jsx
  • Update ListRecipesComponent
  • Create EditRecipeWSComponent

Workshop Branch

Create a branch of development for the workshop. Name it something appropriate like fe-implementation-workshop. Do NOT merge this branch with development. Keep the branch as a record of completing the workshop.

React Overview

index.html

index.html is the default page that is displayed when you navigate to a directory via a web browser. Really, entering a URL in a web browser is essentially navigating to a directory on a remote server. If you do so, the index.html page is the one that is displayed. This is the entry point to our front end application.

For our CoffeeMaker React app, index.html calls the /src/main.jsx script in the body.

TODO: One thing you might notice is that the head tag in index.html include a title of “Vite + React”. Update this to “Coffee Maker”.

src/main.jsx

main.jsx is in the src/ directory and sets up the component hierarchy for the React app by creating the root of the component hierarchy and including App.jsx:

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

No modifications should be made to src/main.jsx.

src/App.jsx

App.jsx sets up the pages for the React app. We have a header, a footer, and the main body of the page. The main body consists of the routes that lists the mapping between URL paths and the associated components. If you want a user to be able to navigate to a path, you need to include that information in App.jsx.

There are already paths for:

  • /: listing all recipes
  • /recipes: list all recipes
  • /add-recipe: adding a recipes
  • /inventory: listing the inventory
  • /make-recipe: making a recipes

You may have edited existing paths or added new ones as you worked on Milestone 3.

For this workshop, we’ll be working with listing all recipes which should be at recipes/.

You’re welcome to change what the behavior at / (or index) is. If you do so, you’ll need to update it in App.jsx by modifying the Route element. You may also update the HeaderComponent and Footer Component.

A couple of hints for adding new routes.

  • Copy one of the existing lines and update with the appropriate path and component.
  • Don’t forget to import the component.
  • Develop incrementally. When you first create a component have it return some basic text to make sure the routes work correctly. Then start updating the component.
  • Frequently check the results of the changes. The React app will automatically load changes so you can practice incremental development. Don’t try to write everything at once!

Components

In React, the component is the main item we work with. Roughly, you should think about a Component as a chunk of functionality, possibly at a page level.

Let’s take a look at the ListRecipesComponent.

Imports

The first portion of any component is the imports section. The ListRecipesComponent imports:

  • React libraries and the useEffect and useState functions from react
  • Functions from a service file
  • Function from react-router-dom which supports moving between components
import React, { useEffect, useState } from 'react'
import { listRecipes, deleteRecipe } from '../services/RecipesService'
import { useNavigate } from 'react-router-dom'

Functional Components

Functional components return a React element as JSX, which allows us to combine JavaScript with HTML. Because JSX follows HTML rules, you must close elements. If an element doesn’t have any children, use the self-closing tag />.

Components should start with a capital letter. The filename matches the component name and ends in .js or .jsx. You should use functional components to build a user interface

The functional component template looks like the following. If you plan to use the component in another component, you need to export the component (the last line of the template). The template below provides a default export. You can only have one default export per file. You can additionally export other named components.

const ComponentName = () => {

   //Javascript functions

   return (
      //JSX with the content of the page
      //This may include dynamic elements	  
   )

}

export default ComponentName

The simplest component in our project is the FooterComponent. It returns well formed JSX (HTML) with footer information. This is a great component structure to start from.

/** Code for the Footer of the web page. */
const FooterComponent = () => {
  return (
    <div>
        <footer className="footer">
            <span>Yay Coffee!</span>
        </footer>
    </div>
  )
}

export default FooterComponent

There are also class components. Think of these like Java classes - they can have state and behaviors. If you want to learn more about class components, refer to the documentation. Our focus will be on functional components.

Embedding JavaScript in JSX

You can embed JavaScript expressions in JSX by wrapping them in curly braces.

If you wrap a variable, the value of the variable will be used.

Properties (props)

Functional components can have arguments, props, which are passed as parameters of the function. The fields of the props are accessed via . notation (e.g., props.name).

const ComponentName = (props) => {

   //Javascript functions

   return (
      <div>
         <p>Name: {props.name}</p>
      </div>	  
   )

}

export default ComponentName

State and the useState Hook

If you would like to work with state variables in a functional component. You will need to import the useState hook from the react libraries.

The useState hook accepts one parameter and the result is assigned to an array that contains the state variable name and the associated setter method for the state variable. Because the setter method is a straight-forward setter, the code is auto-magically created for you behind the scenes. You can then use your setter in other functions or JSX.

The useState method should receive a default value for the variable type. If the state is a string, use “”. If the state is an array (like the list of recipes, below), then use [].

   const [recipes, setRecipes] = useState([])

    function getAllRecipes() {
        listRecipes().then((response) => {
            setRecipes(response.data)  // Calls setRecipes function
        }).catch(error => {
            console.error(error)
        })
    }

Effects and the useEffect Hook

useEffect is a react hook for synchronizing a component with calls to an external system. In ListRecipeComponent use call the REST API via the service functions via useEffect. useEffect must be imported from the react libraries.

    useEffect(() => {
        getAllRecipes()
    }, [])

    function getAllRecipes() {
        listRecipes().then((response) => {
            setRecipes(response.data)
        }).catch(error => {
            console.error(error)
        })
    }

Services

The Services components (in the src/services/ directory) let us interact with the backend’s REST API. We use the axios libraries to make REST API calls.

RecipeService.js is below.

import axios from "axios"

/** Base URL for the Recipe API - Correspond to methods in Backend's Recipe Controller. */
const REST_API_BASE_URL = "http://localhost:8080/api/recipes"

/** GET Recipes - lists all recipes */
export const listRecipes = () => axios.get(REST_API_BASE_URL)

/** POST Recipe - creates a new recipe */
export const createRecipe = (recipe) => axios.post(REST_API_BASE_URL, recipe)

/** GET Recipe - gets a single recipe by id */
export const getRecipe = (id) => axios.get(REST_API_BASE_URL + "/" + id)

/** DELETE Recipe - deletes the recipe with the given id */
export const deleteRecipe = (id) => axios.delete(REST_API_BASE_URL + "/" + id)

There should be a *Service.js for each Controller class in the back end. There should be a call to in the *Service.js for each backend Controller endpoint.

The service is creating the function call (export const functionName). The function parameters are listed in the () if there are any. These correspond to the expected parameters for the REST API end point. Then we call the function for the appropriate HTTP verb. The URL is the first argument. Other arguments follow as appropriate.

Services must be imported in Components. We can call services from getEffect hooks or from other functions.

JavaScript Functions

JavaScript functions are defined within the functional component but before the return call. Functions are defined with the function keyword. ListRecipesComponent defines several functions:

    function getAllRecipes() {
        listRecipes().then((response) => {
            setRecipes(response.data)
        }).catch(error => {
            console.error(error)
        })
    }

    function addNewRecipe() {
        navigator('/add-recipe')
    }

    function removeRecipe(id) {
        console.log(id)

        deleteRecipe(id).then((response) => {
            getAllRecipes()
        }).catch(error => {
            console.error(error)
        })
    }
  • getAllRecipes(): calls the listRecipes() function in the RecipeService.js file. If any recipes are returned, they are set to the recipes state as an array. Otherwise, the error is recorded to the console.

  • addNewRecipe(): navigates the user to the page for adding a recipe.

  • removeRecipe(id): removes the recipe with the given id via a call to the RecipeService.deleteRecipe() function. The recipe is deleted or an error is printed to the console.

The navigator function call is part of the react-router-dom libraries. To use the navigator function (as shown in the addNewRecipe function, above), you first need to create a navigator variable:

    const navigator = useNavigate();
	
	function addNewRecipe() {
        navigator('/add-recipe')
    }

Returned JSX

The return portion of the functional component wraps the JSX that should be rendered by the browser. Dynamic JavaScript elements are wrapped in curly braces.

We use div elements to break the JSX into portions of code. We can nest div elements and apply styles to them through the className attribute. Look up Bootstrap styles to use.

The top level div is the container for the JSX for this portion of the page.

The ListRecipeComponent has a button for adding a new recipe. It then loops through the list of recipes and creates a table row for each recipe with the recipe information and the option to delete the recipe.

Let’s first look at the code for adding a recipe. The text of the button (e.g., “Add Recipe”) is wrapped in the button element. We create a button and style it using several Bootstrap styles. btn provides a common style for buttons. btn-primary tells us the button will be blue. mb-2 provides additional styling (the Bootstrap documentation provides details). The onClick attribute lets us assign a function that is called when the button is clicked. In this case, we call the addNewRecipe function which will navigate us to the /add-recipe page. The Routes in App.jsx will ensure that the flow of control moves to the correct component.

<button className="btn btn-primary mb-2" onClick={ addNewRecipe }>Add Recipe</button>

The next block of code dynamically creates the table. If there are no recipes, only the header row of the table will be displayed. The JavaScript in the tbody tags will take the recipes array (from when we setState) and map each element to a single recipe. For each recipe, we’ll create the row and contents of the row. We can get the contents of the current element via the recipe reference. This is similar to a for-each loop from Java.

            <table className="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Recipe Name</th>
                        <th>Recipe Price</th>
                        <th>Amount Coffee</th>
                        <th>Amount Milk</th>
                        <th>Amount Sugar</th>
                        <th>Amount Chocolate</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        recipes.map(recipe => 
                        <tr key={recipe.id}>
                            <td>{recipe.name}</td>
                            <td>{recipe.price}</td>
                            <td>{recipe.coffee}</td>
                            <td>{recipe.milk}</td>
                            <td>{recipe.sugar}</td>
                            <td>{recipe.chocolate}</td>
                            <td>
                                <button className="btn btn-danger" onClick={() => removeRecipe(recipe.id)}
                                    style={{marginLeft: '10px'}}
                                >Delete</button>
                            </td>
                        </tr>)
                    }
                </tbody>
            </table>

Edit Recipes

Now that we have a general idea of what’s going on, let’s add functionality for editing a recipe. This workshop is set up so that if you already have created some of this functionality as part of M3, it will work around it.

Create an EditRecipeWSComponent

Create an EditRecipeWSComponent. This name should be distinct from other component names in your system.

Update the contents to a simple implementation that includes header text. This will let us test our setup before things get complicated.

const EditRecipeComponent = () => {
  return (
    <div>
        <h1>Edit Recipe</h1>
    </div>
  )
}

export default EditRecipeComponent

Update Routes

Add a Route in App.jsx for the new component. Don’t forget to import!

When we edit a recipe, we will need the name of the specific recipe we’re working with. This name will become a bind variable. We’ll need to specify that as part of the route. This name will need to match the name of the variable we use in the params letter. We’re using incomingName to avoid a collision with the recipe name later.

<Route path='/edit-recipe-ws/:incomingName' element = { <EditRecipeWSComponent /> }></Route>

Test Route

Navigate to http://localhost:3000/edit-recipe-ws and make sure the page is displayed. It should show “Edit Recipe” as a top level heading.

Update ListRecipesComponent

Let’s update the table in ListRecipesComponent to include an edit button. We’ll then create a function so that when we click the button we’re navigated to the edit recipe page and we’ll print the recipe’s id.

Edit Recipe Button

We’re going to add our edit button in the same cell as our delete button. Table cells are wrapped in td elements. Update the cell with the delete button to the following:

<td>
	<button className='btn btn-info' onClick={() => editRecipe(recipe.name)}>Edit</button>
	<button className="btn btn-danger" onClick={() => removeRecipe(recipe.id)}
		style={{marginLeft: '10px'}}
	>Delete</button>
</td>

This will create a new button for editing a recipe. If you refresh the browser, the button should be displayed, but it won’t do anything yet.

Edit Recipe function

Now we’ll create a function that will navigate us to the new component for editing recipes. Add the following function:

function editRecipe(name) {
	console.log(name)
	navigator(`/edit-recipe-ws/${name}`)
}	

This function has a parameter which is the name of the recipe on that row. We log the info to the console for debugging. Then we navigate to the /edit-recipe-ws/:incomingName route, which maps to the EditRecipeWSComponent. We pass the name as a bind variable on the URL. This will let us transfer the data to the `EditRecipeWSComponent.

Update EditRecipeWSComponent

Now we can start working on the EditRecipeWSComponent to display information about the recipe we want to update. Note that this will be a partial implementation to demonstrate working with bind variables; we won’t call a service for updating.

You can also consider combining add and edit functionality into the same component. If you do, you will have conditional structure on if the incomingName exists to determine if you’re adding a new name (e.g., the incomingName doesn’t exist - if (incomingName) would return false) or editing an existing recipe (e.g., the incomingName does exist - if (incomingName) would return true). You can then determine if you would need to make a POST or PUT HTTP request.

Create JSX

We’ll start by creating the JSX structure before adding in dynamic elements. Update return to the following:

  return (
    <div className='container'>
		<div className='row'>
	    	<div className='card col-md-6 offset-md-3 offset-md-3'>
				<h2 className="text-center">Edit Recipe</h2>
				<div className="card-body">
					<form>
						<div className="form-group mb-2">
							<label className="form-label">Recipe Name</label>
							<input
								type="text"
								className="form-control"
								placeholder="Enter Recipe Name"
							>
							</input>
						</div>
						<div className="form-group mb-2">
							<label className="form-label">Recipe Price</label>
							<input
								type="text"
								className="form-control"
								placeholder="Enter Recipe Price"
							>
							</input>
						</div>
					</form>
				</div>
			</div>
		</div>	
	</div>
  )

Create State

We’ll use the useState hooks to create variable/setter pairs for the form elements. Don’t forget to import useState.

const [name, setName] = useState("")
const [price, setPrice] = useState("")

Bind Variable

We’ll now create the connections to the bind variable with the following code. You’ll need to import useParams from react-router-dom. Since we have used the variable name to correspond to the field of our recipe, we will need to use a different name for our params.

import { useState } from 'react'
import { useParams } from 'react-router-dom'


const EditRecipeComponent = () => {
	
	const [name, setName] = useState("")
	const [price, setPrice] = useState("")
	
	const { incomingName } = useParams()

This will create the id variable that we can use in other parts of the component.

Effect Hook

We’ll use the useEffect hook to connect to the API to get the recipe associated with the given id. You’ll need to import useEffect from react and getRecipe from ../services/RecipesService. This function will check to see if we have an id. If we do, we’ll call the setters for the name and price fields. Because we’re using id as an input, we pass it into the useEffect function via the second argument to the lambda expression.

useEffect(() => {
	console.log(incomingName)
	if(incomingName) {
		getRecipe(incomingName).then((response) => {
			console.log("here")
			console.log(response.data)
			setName(response.data.name)
			setPrice(response.data.price)
		}).catch(error => {
			console.error(error)
		})
	} else {
		console.log("not here")
	}
}, [incomingName])

Incorporate Dynamic Elements Into Form

We’ll now incorporate the dynamic elements into the form. This will update the header to include the recipe name and will populate the fields with the name and price of the recipe.

  return (
    <div className='container'>
		<div className='row'>
	    	<div className='card col-md-6 offset-md-3 offset-md-3'>
				<h2 className="text-center">Edit Recipe {incomingName}</h2>
				<div className="card-body">
					<form>
						<div className="form-group mb-2">
							<label className="form-label">Recipe Name</label>
							<input
								type="text"
								className="form-control"
								placeholder="Enter Recipe Name"
								name='name'
								value={name}
								onChange={(e) => setName(e.target.value)}
							>
							</input>
						</div>
						<div className="form-group mb-2">
							<label className="form-label">Recipe Price</label>
							<input
								type="text"
								className="form-control"
								placeholder="Enter Recipe Price"
								name='price'
								value={price}
								onChange={(e) => setPrice(e.target.value)}
							>
							</input>
						</div>
					</form>
				</div>
			</div>
		</div>	
	</div>
  )

Commit/Push

Don’t forget to tie the commit to the issue as part of the commit message!

When you’re done with the workshop, check off all the todos in the appropriate issue and close the issue.

Do NOT merge the workshop branch back to main.

You are welcome to use code from this workshop in your full implementation if appropriate for your design.

Onward

This should fill in the last missing piece for implementing the front end of the Coffee Maker system. The provided code and the internet should help you finish the implementation.

Do NOT merge the workshop branch back to main. You are welcome to use code from this workshop in your full implementation if appropriate for your design.

Return to the main page for the team and individual tasks.