What I'm Attempting To Do:
Have a list created from an API that lists several teams, each linked to a new team page via their team ID. Example:
Homepage: Localhost:3000/
Lists several options:
Search By Team
Search By Player
click on Search By Team, listing each team Localhost:3000/teams
Gladiators
Maniacs
Click on Maniacs localhost:3000/Maniacs
So far when I click on each team, it takes me to the 404 page.
What I Have Now:
App.js
<Route path="/teams" component={Teams} exact></Route>
<Route exact path='/:teamName' component={EachTeam} />
Standings.js
import Atlantic from "../components/divisions/Atlantic"
function Standings() {
return (
<div className="teams-container">
<Atlantic />
</div>
)
}
export default NHLStandings
Altantic.js
import { Link } from 'react-router-dom';
import { useState, useEffect } from 'react';
function Atlantic() {
const [teams, setTeams] = useState(null);
useEffect(() => {
getData();
async function getData() {
const response = await fetch("RANDOM_API);
const data = await response.json();
setTeams(data) ;
}
}, []);
return (
<div className="container">
{teams && (
<div className="container">
<h2>Atlantic Division</h2>
{teams['teams'].map((team, index) => (
(team.division.name === "Atlantic" && (
<Link
to={`/${team.teamName}`}
teamName={team.teamName}
key={index}
className="team-container"
>
<h2>{team.name}</h2>
</Link>
))
))}
</div>
)}
</div>
)
}
export default Atlantic
EachTeam.js
import { Link } from 'react-router-dom';
import { useState, useEffect, useSelector } from 'react';
function EachTeam(props) {
return (
<div className="container">
<h1>{props.teamName}</h1>
</div>
)
}
export default EachTeam
Apologies for the length, I did not want to omit anything. Thanks in advance for any help.
CodePudding user response:
teamName
isn't a valid prop on either the Link
component or the Route
component. The extraneous props are ignored. I suspect you are navigating correctly and just seeing props.teamName
as undefined.
{teams['teams'].map((team, index) => (
(team.division.name === "Atlantic" && (
<Link
to={`/${team.teamName}`}
teamName={team.teamName} // <-- ignored, not a Link prop
key={index}
className="team-container"
>
<h2>{team.name}</h2>
</Link>
))
))}
To resolve you can access the route match params to get the teamName
. In function components use the useParams React hook.
Given:
<Route exact path='/:teamName' component={EachTeam} />
EachTeam
import { useParams } from 'react-router-dom';
function EachTeam(props) {
const { teamname } = useParams();
return (
<div className="container">
<h1>{teamName}</h1>
</div>
)
}