Home > Net >  How to list out NextJS router param array
How to list out NextJS router param array

Time:03-09

I have a NextJS catch all route which pulls in

import { useRouter} from 'next/router'

And retrieves all the parameters:

const { params = [] } = router.query

If I log the params value I see all the URL path elements in the console.

I would like to repeat out all the params values in an unordered list:

return <ul>
  {params.map((param) => {
    <li>{param}</li>
  })}
</ul>

But this outputs nothing. There are no elements displayed.

How can I get this to display the list?

CodePudding user response:

I think you have a problem with your .map function. Try doing this instead:

return params.map((param) => param);

This will just print your params together in a single line. You can improvise the format in which you would actually want it.

CodePudding user response:

With curly braces you will have to write the return keyword too.

return <ul>
  {params.map((param) => {
    return (<li>{param}</li>);
  })}
</ul>

This is how arrow functions work in JS.

With the current code, there is no return statement basically. So by default undefined is returned and nothing is rendered :

return <ul>
  {params.map((param) => {
    <li>{param}</li>
    //No return statement  
})}
</ul>

For short : You can remove the curly braces.

return <ul>
  {params.map((param) => <li>{param}</li>)}
</ul>
  • Related