After this code-along section, you will be able to:
- Describe React Router's main features: routing, components, history
- Use React Router t" map URLs to components
- ";se React Router to create links to different pages
It's great that HTML5 introduced new browser history mechanics to make it easier for us as developers to build Single Page Applications, and it's important to know what's going on under the hood.
However, on an important note - we're actually not going to be using these new features directly ourselves!
Instead, we'll use a tool called React Router, which bundles everything together so we don't have to worry about it.
For an intro to React Router, watch this video
React Router is a third party library that makes it easy for us to route URLs - not to different pages, but by dynamically loading different components on the same page as the user navigates to different URLs. Once we define how the URLs are routed to the components, React Router will manage our Single Page App's browser history automatically.
Here's what React Router provides:
- Routing: easily define what content is associated with what URLs.
- History: automatically manage browser history when the user navigates between content.
React Router is actually a third-party library. "Third-party" just means it's not built by React and not built by ourselves; it was written by some other "third-party" group of developers. Even though React Router is third-party software, it's extremely useful, trustworthy, and popular - don't be afraid to use it. With more than 20,000 stars on Github, itβs safe to assume React Router is here to stay.
So let's use it!
We're going to make an example website for a Dental Spa business that has:
- A
Home
page. - A page that lists available
Services
. - A page displaying
Contact
information.
Each of these pages of content will be built into their own regular React component; then we'll create a unique URL route that leads to each component.
Here's how we'll route our single-page application:
URL Route | Component | Content Description |
---|---|---|
/ | <Home /> |
A homepage with welcome text. |
/services | <Services /> |
A list of all services provided by the dental spa. |
/contact | <Contact /> |
A page with an address, phone number, and email. |
/services/:id | <Service /> |
Will render beneath Services and shows details about a specific service |
Remember, the URL routes are paths off our main website. We could put our website at any domain, like www.ourdentistwebsite.com
or www.premiumdental.com
, and the URL route paths would behave the same. Paths only care about what comes after the domain name.
Our routes say that if someone goes to ourdomain.com/
they will see our home page with welcome text.
- The content of this page will all be defined in its own
Home
component in a file calledHome.jsx
. - If someone navigates to the URL
ourdomain.com/contact
, they will see content with the business address, a phone number, and an email. All of this content will be defined in a component calledContact
in a file calledContact.jsx
.
In the below codealong, we will walk through building this out together.
You can see a live working copy of the site here.
You are going to follow along, so that you have a locally working React Router application! However, if you'd like at any point to refer to the finished code, you can see all of the final code here.
Remember to stop any React project you currently have running!
Now let's make the dentist project. In your terminal, use create-react-app
to make a new project called dental-spa
:
$ create-react-app dental-spa
$ cd dental-spa
$ npm start
Your browser should open to http://localhost:3000/ and you'll see the standard "Welcome to React" message with a fancy rotating atomic icon. create-react-app
creates several files for us in a directory called src
. Open the App.jsx
file in your editor.
Remember, App.jsx
contains our main application (it's what's called by index.jsx
). You should see the basic JSX structure of the standard React starter page. Make sure the file is the same thing you're looking at in the browser by finding the text Welcome to React
inside an <h2>
element.
Change the text to say Hello!
, save the file and make sure you see the changes automatically appear in your browser.
If it doesn't automatically refresh, then try to manually refresh the page. If you still don't see changes after a manual refresh then something could be wrong. Make sure you're editing the right file.
Pro tip: It's a good idea to make simple, verifiable changes like this when you're first starting a project. It's a good sanity check.
Make sure you can do simple things first. Don't start with complex things; complex changes come with greater potential for error. Prove to yourself the small changes work, and you'll save yourself headaches debugging large complex changes.
Let's install React Router.
Since React Router is a third-party library, we'll need to use to download React Router and save it as a dependency in our project.
In your terminal, enter:
$ npm install react-router-dom
You can either create a new tab in your terminal or hit
ctrl-c
to stop the running app, to use the terminal!
Let's start the app again. Enter the command npm start
in your terminal.
Let's get rid of the standard "Welcome to React" page and replace it with our own dental spa home page. Continue editing App.jsx
: take out most of the JSX contents, and delete the import statement for logo.svg
, which we won't use.
The App.jsx
file contains one component that our whole app will live inside of. Remember that React components have a return value from the main function (or from the render method if they're class-based) that defines what the component will look like when it is rendered on the webpage.
Reminder! That UI value must have at most one top-level element. It's common to wrap everything in your component in a
div
to make sure you satisfy this constraint.
So...
Let's add one <h1>
that says Dental Spa
and a paragraph with some short welcome text. Your App.jsx
file should now look like the code below. Save the file and check your browser to make sure the changes show up.
App.jsx
function App() {
return (
<div className="App">
<h1>Dental Spa</h1>
<p>Welcome to my dental spa.</p>
</div>
);
}
export default App;
Great! Now we have a simple homepage set up. Let's move on to getting the rest of the content for our site set up.
We've been editing App.jsx
, which defines one component for our entire application. So far our app manually shows just the homepage. Let's refactor this so the content of the homepage is moved into its own component called Home
.
- Create a new folder in
src
calledcomponents
- In that folder, make another folder called
pages
(this will hold the components that render whole pages!) - Create a new file in your
pages
folder calledHome.jsx
. - Write a basic component and move the content of your
return
statement inApp.jsx
to thereturn
in yourHome.jsx
component. - Go back to the
App.jsx
file and delete the<h1>
and<p>
tags where we used to have content written directly inside ourApp
component. We don't need that written insideApp
any longer, because we just moved it all to the newHome
component. - Instead, we need to call our new component. Put
<Home />
inside the<div>
in theApp
component. This tells theApp
component to render theHome
component right there inside the div. - Don't forget to import it at the top of
App.jsx
.
Your App.jsx
and Home.jsx
files should look like this after you've properly created and imported the Home
component.
App.jsx
import Home from "./components/pages/Home";
function App() {
return (
<div className="App">
<Home />
</div>
);
}
export default App;
Home.jsx
function Home() {
return (
<div className="Home">
<h1>Dental Spa</h1>
<p>Welcome to my dental spa.</p>
</div>
);
}
export default Home;
The purpose of our site is to create several components that we can swap out as the main content of the main page of our application in order to create a modern Single Page Application. We'll create two more components, and then we'll start routing things up.
- Create a new file called
Services.jsx
- Create a new file called
Contact.jsx
To create these new files, follow the same procedure we used to create the Home
component. Basically, we used the App
component as a template: create each file, change the name of the component to its new name, then replace the JSX in the return value with custom content. Be sure to import each new component into App.jsx
just like we did with the Home
component!
You can put your own content to be rendered by each component if you'd like.
Now that we have our components made, there's nothing stopping us from importing multiple components into our App.jsx. So now, we have:
App.jsx
import Home from "./components/Home";
import Services from "./components/pages/Services";
import Contact from "./components/pages/Contact";
function App() {
return (
<div className="App">
<Home />
<Services />
<Contact />
</div>
);
}
export default App;
Check yourself! You should see all of content for each of the pages all stacked on top of each other on the homepage. If you don't see content from all three of your components, something is wrong. You must fix this before continuing. Always do simple things before doing complex things!
Try manually deleting two of the three components so only one component is left on the page at a time. You should see your webpage update with just that component. This is effectively what React Router does. We can configure React Router so that it's aware of which component we want to show on the screen, and React Router will swap the components out so that only the correct one is shown at a time.
Now that we've proven to ourselves that we're able to show each of the components on the main page, it's time to hook them up to Router.
Here's the general syntax for creating routes. React Router uses some of its own components to define how URLs are routed to your components and to create links to those routes. You must have one <Router>
component that wraps itself around multiple <Route>
components. Each <Route>
component has two pieces:
path
- defining the URL path that leads to the component.component
- defining what component users will see when they navigate to the path.
Delete what is currently returned in the return
for your App.jsx
function, and replace it with a Router component call with three routes, as shown below.
class App extends Component {
render() {
return (
<Router>
<main>
<Route exact path="/" component={Home} />
<Route path="/services" component={Services} />
<Route path="/contact" component={Contact} />
</main>
</Router>
);
}
}
There are three other important things to note here:
- This goes in place of your existing component calls of
<Home />
,<Services />
and<Contact />
(depending on which syntax you went for). - The first route for the homepage at the root URL path
/
uses a special extraexact
attribute before defining the path. Theexact
attribute means the component associated with the route will only be shown if users are at exactly that URL path. If you forget to include theexact
keyword, when someone navigates to/contact
they will actually see two components, because/
is a partial match for/contact
. - Notice that all of the
<Route>
components are wrapped inside one tag,<main>
. Likerender
, the<Router>
element can only have one direct child element. If you don't wrap the routes with a tag like<div>
or<main>
, the page will appear blank, and you'll have to open your JavaScript console to see that there's an error being logged to the console. Like so -
Pro tip: It's a good habit to check the console for errors whenever your app is not behaving as expected.
In order to use the React Router components in App.jsx
, you'll need to import them. This import syntax allows us to grab several specific components out of the react-router-dom
library at once. So far we've used Router
and Route
.
The Router component is actually called BrowserRouter
inside the library package, but we'll use the as
keyword to rename it to
Router
so it's easier to remember.
While we're here, we'll also import a third component, Link
, which we'll get to in a minute.
Put this code at the top of your App.jsx
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
Here's how the imports and all the components look like together for our dental spa:
App.jsx
import React, { Component } from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./components/pages/Home";
import Services from "./components/pages/Services";
import Contact from "./components/pages/Contact";
class App extends Component {
render() {
return (
<Router>
<div>
<Route exact path="/" component={Home} />
<Route path="/services" component={Services} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
}
export default App;
Now that everything is hooked up you can manually enter different URLs and see how your page appears. If you go to http://localhost:3000/, you should see just the homepage. If you go to http://localhost:3000/services, you should see just the services page. If you go to http://localhost:3000/contact, then you should see just the contact page.
Check it!
- Make sure that React Router is routing from each URL to the proper component correctly.
- Double check to make sure that the home page doesn't display at the same time as another component. If the homepage is shown while you're at the path to
/services
or/contact
then you probably did not write theexact
keyword when you defined the/
Home route.
Let's intentionally make an error. Delete the exact
keyword off the Home route. Navigate to the /services
page and the /contact
page again and see how the components are displayed. You should see the content of the homepage and the content for one of the other pages at the same time, with the home page on top.
Now add the exact
keyword back to the home route and notice that the pages don't double up any more.
Two common errors:
- If the page appears blank, open the JavaScript console to see if there are errors. Chances are you have a typo somewhere or forgot to make sure the
<Router>
only has one child element. Remember, wrap all of your<Route>
components in one parent HTML element (we're usingmain
). - If multiple components appear on the page at the same time there's something with how you've routed URLs. Make sure you use the
exact
keyword on the root path/
and make sure there are no duplicate URL paths defined anywhere.
Great, now our site is up and running! We can manually type in URLs and see the different pages.
Although... users never really type URLs, do they? We should probably have links at the top of the page so we can just click on things. We could build this ourselves, but we don't have to! Remember that Link
component we imported from React Router?
Just like links in HTML, we can wrap <Link>
tags around whatever text that we want to display to the user to click on. The pieces of this are:
<Link>
- creates<a>
tags and automatically integrates modern HTML5 browser history mechanics for the Single Page Application. It has one attribute:to
- what path to navigate to when the user clicks the link
We'll add one <Link>
component that leads to each of our different content pages.
<Link to="/">Go to Home Page</Link>
<Link to="/services">See Our Services</Link>
<Link to="/contact">Contact Us!</Link>
Did you notice that we don't reference components here? We simply make links for users to click that connect to URLs, and the
Router
section in the code handles the actual component changes.
We can include those links in a <nav>
element at the top of our page. It will stay on the page permanently, and the different components will be swapped between each other below it. There's actually nothing special about the <nav>
element. It behaves exactly like a <div>
. <nav>
is just a semantic element that gives your JSX more meaning when people read it.
In your App.jsx
, inside the <Router>
(because we want it rendered!) and before the Route
statements, put:
<nav>
<Link to="/">Go to Home Page</Link>
<Link to="/services">See Our Services</Link>
<Link to="/contact">Contact Us!</Link>
</nav>
So, our web app now looks like the left image - but do you see a difference between the left and the right?
There's one slightly annoying thing about React here - React strips out whitespace (e.g., spaces, returns, tabs) between elements. If we write <Link>
components next to each other, even if they're on new lines in our code, React strips all of the whitespace between them and squishes them all together.
We must insert a space manually by writing {' '}
in order to get spaces between our links. We'll do that but add a bit of pizzazz by also adding a |
.
So instead of the code we used before, here is how we'll format the links. Nothing has changed except that we've added the space:
<Link to="/">Go to Home Page</Link>{' | '}
<Link to="/services">See Our Services</Link>{' | '}
<Link to="/contact">Contact Us!</Link>
And now the nav bar will have spaces like it should. Try it!
Here's what our final App.jsx
looks like:
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./components/Home";
import Services from "./components/pages/Services";
import Contact from "./components/pages/Contact";
function App() {
return (
<Router>
<div className="App">
<nav>
<Link to="/">Home</Link>
{" | "}
<Link to="/services">Our Services</Link>
{" | "}
<Link to="/contact">Contact Us!</Link>
</nav>
<Route exact path="/" component={Home} />
<Route path="/services" component={Services} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
export default App;
Check it out! Does yours work?
You can see how the number of components can really start to stack up. Code organization is very important while also being hotly debated. We've already stared the organization process by creating nested folder structure for our components (/components
and /pages
), let's add a bit more to that.
We're going to create another folder in components
called partials
; this will hold things like our Header
or Footer
, but can also contain components like Button
or Alert
.
We're going to create a component called Header
which will contain our nav
and nested Link
tags. We'll wrap it all in a <header>
tag to maintain semantic structure. This also allows us to add a bit more to this header later if we want (Like a logo).
REMEMBER! Since we're taking our <Link>
components out of App.jsx
, we'll need to import them, same as any other imported component.
Here's what your Header.jsx
should look like:
import { Link } from "react-router-dom";
const Header = () => (
<header>
<nav>
<Link to="/">Home</Link>
{" | "}
<Link to="/services">Our Services</Link>
{" | "}
<Link to="/contact">Contact Us!</Link>
</nav>
</header>
);
export default Header;
Next, head to your App.jsx
and replace the nav
with our newly created Header
component! Much cleaner and well organize! Marie Kondo would be proud!
Remember to import
Header
and remove our import ofLink
since we aren't using it.
Our Router functionality right now is very cool but it lacks some very important functionality. We only know how to render a default component but we know that we frequently want to give our components props. How do we do that with React Router?
It's actually very easy. Inside of our <Route>
s we've been using the component
attribute. If we want more custom control, we can use a function instead but we must change the attribute from component
to render
. First, let's simulate some data by adding a simple array into our App's function:
const services = [
"Drillin' And Fillin'",
"Molar Massage",
"Cucumber Mask (but for your cavities)",
];
return (
// ...
}
We would normally want to pass this data into our Services component as props but there is no way to do that with the component
attribute. Let's change it to render
:
...
<Route exact path="/" component={Home} />
<Route path="/services" render={() => <Services services={services} />} />
<Route path="/contact" component={Contact} />
...
By using render
we can pass in a function that will render a component. We can pass in our services now as props. We must use render
and pass in a function in order to render a component with props.
Let's update out Services component to render this new data. Go into the Services component and add the mapping to render this array into the page nicely.
Remember that for functional components, you take props in as a parameter in your function's parens, and you do NOT use
this
. (You're only using that parameter's value just like in any other function!)
The last thing we need to know how to do in Router is pass parameters via our routes. Recall that we were able to do this in Express by including a colon in the route path followed by a variable name:
app.get("/widgets/:id", ...)
This allows a variable value to be passed in as part of the URL. When this value landed in our route, we were able to access it via req.params
.
React Router has very similar functionality. When we are defining the paths in our <Route>
components, we can specify a route parameter by including the same colon followed by a variable name:
<Route path='/widgets/:id' ...
Now, we can put variable values onto the end of our Link URLs when linking to this Route. But where do they show up? There is a special set of props that are passed into our component from the Route component but we have to add a little code to make them show up. First, the router must be using the render
method and not the component
method. This is because we must pass in props. Set your parameterized route up like so:
<Route path="/widgets/:id" render={(props) => <WidgetShow {...props} />} />
// Router provides the props here ^^^^^ and we pass them in ^^^^^ here to our component.
That syntax {...props}
is unpacking all of the props in the props object so that they are passed into our component as individual props.
More info on the Spread Syntax can be found at MDN
The one we are interested in is called match
. We can find it in our component in props
for class-based components or just props
for function-based components. Here is how we might access it in our component:
function WidgetShow(props) {
return (
<div>
<h1>You entered this URL parameter: {props.match.params.id}</h1>
</div>
);
}
export default WidgetShow;
Because the route parameter is passed in via props, we can easily reference it to find the item associated with the parameter. Frequently, we use this to display the details of one specific item in a collection, like in our READ ONE routes.
Let's use this functionality to render a component that shows more about a specific service! We'll need to:
- Make some fake data.
1.1. Make a folder for
data
. 1.2. Make a.js
file that will export our data so we can import it to our relevant components (eventually this will be data received from querying and API). - Make our component.
- Implement the route for it.
- Search through the data to get the relevant information based on our URL parameter.
Visually, we'll have the Service
component render underneath our Services
component.
Pop Quiz! What will our route need to start with in order to accomplish this?
We're organizing our code, so based on our current file structure, where do you think our data
folder should live? Why do you think it should be there?
src
is shorthand for source
, which means our resources need to be in that folder. Our data isn't a component, so it doesn't make sense to put it in there. That leaves us creating a folder in src
called data
!
Since we haven't learned how to query an API in React yet, we're going to make a javascript file that we can then import and utilize! Let's make a serviceDetails.js
in our data
folder.
In order to mimic data that might be received from and API, we are going to create and export an array of objects for our services. Create a variable called serviceDetails
that is an array. For each of our services listed in App.jsx
, we're going to make an object that has the keys id
, name
, price
, and description
. Feel free to take some time to create this yourself, or copy this data below!
const serviceDetails = [
{
id: 1,
name: "Deep Cleaning",
price: 80.8,
description:
"Why settle for surface cleaning when you can clean deep in your teeth's spirit? With Dental Spa's Deep Cleaning, your smile will be shining just as bright as your aura.\nTake a journey with us as we lift your smile and your spirit to new heights. The deep cleaning starts with a scrub to remove the plaque and bad vibes off your teeth. This is followed by sonic therapy where we put a bell in your mouth and ring it in fibonocci sequence time. The session concludes with a hot mouth press where we wrap your teeth in freshly made toast (Gluten free options are available).",
},
{
id: 2,
name: "Filling",
price: 133.99,
description:
'We will remove the decayed portion of the tooth and then "fill" the area on the tooth where the decayed material was removed. These are also used to repair cracked or broken teeth and teeth that have been worn down from misuse and the pull of Mercury in retrograde.',
},
{
id: 3,
name: "Gum Massage",
price: 40.03,
description:
"A luxureous treatment at a reasonable price! Dental Spa's world-renowned gum massage invovles our denticians rejuvinating your teeth holsters with dead sea salt, turkish hamam oil, and lotus petals. You'll leave with the softest gums around and something to brag to your friends about",
},
{
id: 4,
name: "Root Canal",
price: 240.98,
description:
"Root canal is our treatment to repair and save a badly damaged or infected teeth instead of removing them. We clean the canals inside a tooth's root. This endodontic treatment replaces the pulp tissue of your teeth with organic potato starch in a cutting edge technique soon to be approved by the FDC.",
},
{
id: 5,
name: "Oral Mud Bath",
price: 100.0,
description: "We shove your face in mud. Very good.",
},
];
We're going to start by simply stubbing out our route. After we implement the route in our Router
, we'll go back to it and make sure that we're able to access the parameters.
We could put this in pages
or partials
. What are the arguments for putting it in one? What about for the other?
For now, make a Service.jsx
component in pages
since we're going to be using a route for it. To stub it out, simply have a div
with an h3
for the name, an h6
for the price, and a p
for the description. It should look something like this:
Now that we have a stubbed out route, we need to see if we can render it! In our App.jsx
, let's add another Route
to /services/:id
. Let's write it the same way that the notes above wrote Widget
, passing props into the anonymous function and then using the spread operator to pass those to the component itself.
Remember to import your component!
Now, go to http://localhost:3000/services/test
to see if your stub is rendering! If not, check your App.jsx
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./components/Home";
import Services from "./components/pages/Services";
import Contact from "./components/pages/Contact";
import Header from "./components/pages/partials/Header";
import Service from "./components/pages/Service";
import services from "./data/servicesDetails";
function App() {
const services = [
"Drillin' And Fillin'",
"Molar Massage",
"Cucumber Mask (but for your cavities)",
];
return (
<Router>
<div className="App">
<Header />
<Route exact path="/" component={Home} />
<Route
path="/services"
render={() => <Services services={services} />}
/>
<Route path="/service/:id" render={(props) => <Service {...props} />} />
<Route path="/contact" component={Contact} />
</div>
</Router>
);
}
export default App;
Once that's working, we need to check to see if we can get the parameters! In Service.jsx
, replace what's in the h3
tag with props.match.params.id
. Now if you go to http://localhost:3000/services/hello
, your component will greet you!
We can either get data in App and then render our component with specific info or get the data in the component and filter out what we need there. Since we have to get all the data at once, it makes more sense to do that in App.jsx
.
Importing data from a file is as easy as import movies from './data/movies'
. In our case, we will import serviceDetails
and the link will be relative to our App.jsx
(./data/serviceDetails.jsx
). If we want to check if we imported it correctly, we can console log it in our function.
The render
function in our Route
component call requires an anonymous function. Since that function gets passed props
, we are going to use that to get the match
value and use that with Javascript's built-in find function to get one service and then pass that down to our Service
component.
The
find
function is an array method.let matchedElem = array.find(arrayElem => arrayElem === conditional)
Up until now, we've been using ES6's implicit return with the anonymous functions passed into render
. However, we want to get the specific service after the route has been called (otherwise we don't know which service they are requesting) but before the component is rendered, so are going to perform javascript logic in there BEFORE we actually render the component.
In the render
function of our Service details route, we'll use array.find
to find a service by comparing the id
key in a service object with the id acquired from props.match.params.id
.
How would we use array.find
to acquire a specific service using the data we have available?
Hintssss
- We know we need an array to iterate over; which array holds a list of all our service objects?
- We know that the function passed to
array.find()
needs to return a boolean. What conditional statement can we return in order to find equality between theid
found in a service object with theid
received from the url parameters? - If we use the identity operator, how will we account for different types? (
id
in our service object is a number, but theid
from params is a string) - How do we reference the result of the find later?
Take 5-15 minutes to try to figure out how to implement this. If you get stuck, look at the hints as well as documentation on array.find()
Depending on what your component needs, some developers will get just
match
fromprops
using destructuring. Many developers who use React Router will use this kind of object destructuring in their code. Note that this method makes other default props (likeprops.history
) properties unavailable to this component.
<Route
path="/services/:id"
render={({ match }) => {
let id = match.params.id;
return <Service id={id} />;
}}
/>
const service = serviceDetails.find(
(service) => service.id.toString() === props.match.params.id
);
Now that we have a specific service object, we can now pass that into our Service
component. There are a couple of ways that we can do this:
- Pass
Service
a prop calledservice
which is the object found by thearray.find()
function. Information will have to be accessed byprops.service.name
etc which might get messy in our code - Explicitly pass the service values as individual props to our
Service
component. Each value will be added to theprops
object and can be accessed byprops.price
etc which can get messy when we return our component - Use the spread operator to add the values in
service
toprops
and then use object destructuring syntax (also...
) to pass each of those values to our component. Each value is still added to theprops
object and accessed through it, however it may be easy to overlook what is actually being passed into a component.
We'll use the 3rd method, but each of them has their merits. If you want to choose a different method, then go ahead, but make sure you know how you will reference that data in your Service
component.
<Route
path="/services/:id"
render={(props) => {
const service = serviceDetails.find(
(service) => service.id.toString() === props.match.params.id
);
props = { ...props, ...service };
return <Service {...props} />;
}}
/>
First, it is getting awfully tiring to write out these URLs ourselves, so we are going to pass our serviceDetails
array to Services
instead of our array of strings. Instead of rendering a list of strings, our Services
page will now Link
to each service!
Step one is to change what array is passed to our component in App.jsx
. Change <Services services={services} />
to <Services services={serviceDetails} />
.
Next, we need to change what our map
function returns in Services.jsx
. Right now, we're just returning a list item with a string of the service name. We are going to instead return a Link
component that links to /services/:id
for each service.
Hintsssss
- You'll need to import the
Link
component. - the
to
prop passed intoLink
is just a string, concatenate it so it goes to the appropriateid
Check your work (it doesn't have to look exactly like this, but is functionally similar)
import { Link } from "react-router-dom";
function Services(props) {
return (
<div>
<h1>These are the services we provide:</h1>
{props.services.map((service) => (
<div>
<Link to={`/services/${service.id}`}>{service.name}</Link>
</div>
))}
</div>
);
}
export default Services;
Once we've got the links working, we need to update our component to render the service information it has been given! Replace the <h3>
with the service name, the <h6>
with the price, and the <p>
with the description!
Your code may look a little different if you choose to pass your service data to Service differently.
const Service = (props) => (
<div>
<h1>{props.name}</h1>
<p>${props.price}</p>
<p>Description: {props.description}</p>
</div>
);
export default Service;
Finally, we want to add a bit of conditional styling; if someone has gone to an id that doesn't exist yet, we want to display an <h3>
that simply tells a user that there is not yet a service with that specific id. We'll use and if...
statement in the render
function of our Service
component to render the warning if there is no name (it won't get passed down if the array.find()
method in App.jsx
didn't match anything). Else, return as normal!
Because the code block of the
if
statement is areturn
statement, we don't need to explicitly useelse
;return
exits the function, so any code after it doesn't get run! But if that condition isn't met, then that initialreturn
statement never gets a chance to run, so our normal display shows.
Because we changed the Service component to have lines of code that AREN'T being returned, we'll need to convert the function to use curly braces after our arrow. Parens were fine when we were just saying, "All of this gets reutrned!", but now we have some logic in there, so it's more of a full old-style function.
ALTHOUGH, if you want to get really fancy, you could keep the parens and make the whole thing a ternary statement. If you want to work on your chops, see if you can find a way to keep those parens!
const Service = (props) => {
if (!props.name) {
return <h3>That is not a service we have yet!</h3>;
}
return (
<div>
<h1>{props.name}</h1>
<p>${props.price}</p>
<p>Description: {props.description}</p>
</div>
);
};
export default Service;
Or, with a ternary to avoid the curlies:
const Service = (props) =>
!props.name ? (
<h3>That is not a service we have yet!</h3>
) : (
<div>
<h1>{props.name}</h1>
<p>${props.price}</p>
<p>Description: {props.description}</p>
</div>
);
export default Service;
`
Try putting in http://localhost:3000/services/test
to see if you get your conditionally rendered message!
This Dental Spa has all the functionality, but it's look doesn't match the soothing services the Dental Spa offers. Spend some time making it look nice (or especially horrible). Have fun at the Dental Spa!