0

Params is undefined in ItemPage. I can't seem to see the issue here. Any takers?

Basically trying to create a dynamic path with Link .

export default function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/catalog"  component={Catalog} />
        <Route path="/about"  component={About} />
        <Route path="/item/:nm" component={ItemPage}/>
        <Route render={() => <h1>404: page not found</h1>} />
      </Switch>
    </Router>
  )}
function Catalog() {
  return (
    <div className="Catalog">
        {Routes.map((route, index) => {
            return <p key={index}><Link to={`/item/${route.name}`}> {route.name} </Link></p>
        })}
    </div>
  );
}
const ItemPage = ({match:{params:{nm}}}) => {
return (
  <div>
    <h1>Item {nm} Page</h1>
    <ItemPage name={nm}/>
  </div>
  )
  };

3 Answers3

0

if you use react-router-dom package, then this method might help you then:-

  • ItemPage (use useParam hook):-
import { useParams } from 'react-router-dom'

const ItemPage = () => {
  const { nm } = useParams()

  return (
    <div>
      <h1>Item {nm} Page</h1>
      <ItemPage name={nm}/>
    </div>
  )
};
lala
  • 1,309
  • 9
  • 21
0

I'm not sure if the way you have your props set up on ItemPage is exactly correct - in my experience using react-router I've always just used match as its own parameter without defining its properties like so:

const ItemPage = ({match}) => {
  return (
    <div>
      <h1>Item {nm} Page</h1>
      <ItemPage name={match.params.nm}/>
    </div>
  )
};

Another option could be to use the routecomponent props and do some destructuring to pull out match:

import { RouteComponentProps } from 'react-router';

const ItemPage : FC<RouteComponentProps> = (props) => {
  const {match} = props
  return (
    <div>
      <h1>Item {nm} Page</h1>
      <ItemPage name={match.params.nm}/>
    </div>
  )
};

(see here: What TypeScript type should I use to reference the match object in my props?)

Ben
  • 62
  • 1
  • 8
0

Basically the nested <ItemPage name={nm}/> was the issue. It should be replaced with a different component or HTML.

https://github.com/Tyler90901/webtech/pull/1/commits/16b337bc2e45ef0f06bc41f1fc060b87a8bc9d36