Skip to content
Advertisement

How to list out NextJS router param array

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?

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement