-1

I'm quite new to react and trying to understand how to pass props.

1st i have set a Navlink component which holds a subcategories property :

<NavLink
  catid={category.id}
  to={category.route}
  catname={category.name}
  subcategories={category.subcategories}
>
  {category.name}
</NavLink>

{category.route}, {category.name}, {category.subcategories} are fetched from json file, so this part is OK.

Each route is defined so:

<Route
  path='/epicerie-sucree'
  render={(props) => (
    <CategoryPage
      {...props}
      catid={10}
      catname={"Epicerie sucrée"}
      subcategories={props.subcategories}
    />
  )}
/>

so it renders a component named <CategoryPage/>

And here's the code of the CategoryPage Component :

export default function CategoryPage(props) {  
  return (
    <div>
      {  props.subcategories.map(subcat => (
            <div>{subcat.subcat_name}</div>
      ))}
      <FooterCat cat={catData.categories}></FooterCat>
    </div>) 
}

So the categoryPage component should receive correctly the props transmitted through the router, no ?

Instead it throws an error "TypeError: Cannot read property 'map' of undefined" I don't understand... Thanks

3
  • you should pass the props as url parameters and define the urls accordingly Commented Apr 23, 2020 at 8:13
  • It would be good if you add json file content in same structure. Commented Apr 23, 2020 at 8:16
  • @Sameer Reza Khan. Here it is api.jsonbin.io/b/5ea1636098b3d53752331597 Commented Apr 23, 2020 at 9:45

1 Answer 1

2

NavLink won't pass props to the component being rendered by the route, but what you can do is to pass some "state" with the route push that occurs. The render prop passes the route-props to the component and you spread that to the CategoryPage component.

<NavLink
  to={{
    pathname: category.route,
    state: {
      catid: { category.id },
      catname: { category.name },
      subcategories: { category.subcategories },
    }
  }}
>
  {category.name}
</NavLink>

Now the state will be passed with the route push on the location prop.

props.location.state.subcategories

Component

export default function CategoryPage(props) {  
  return (
    <div>
      {
        props.location.state.subcategories.map(subcat => (
          <div>{subcat.subcat_name}</div>
      ))}
      <FooterCat cat={catData.categories}></FooterCat>
    </div>) 
}

May need to do the same for catData.categories as it isn't clear what that is

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.