Home > other >  Error with rendering a sorted array in next.js
Error with rendering a sorted array in next.js

Time:07-18

I am trying to render an array of items based on their value (highest to lowest). Everything works fine but I am getting an error saying Error: Text content does not match server-rendered HTML. whenever I run the code. Below is the code used to sort through the array items and map out each item based on its value. I am not sure how to prevent this error.

const items = [
    {id: 1, title: 'Topic 1', value: 2},
    {id: 2, title: 'Topic 2', value: 5},
    {id: 3, title: 'Topic 3', value: 1},
    {id: 4, title: 'Topic 4', value: 4},
    {id: 5, title: 'Topic 5', value: 3},
]

const App = () => {
    <div className="flex flex-col gap-4 w-full p-6 items-center">

    {items.sort((a, b) => b.value - a.value).map((item, index) => (
        <div 
            className="flex gap-2 px-4 items-center h-10 w-full rounded-md text-lg bg-[#ffd700]"
            key={index}
        >
            <div>
                {item.title}
                {item.value}
            </div>
            /5
        </div>
     ))}

    </div>
}

CodePudding user response:

For any future readers; the error can be fixed simply by including the list of whatever you are trying to sort inside of the main function.

For example:

const App = () => {
    const items = [
        {id: 1, title: 'Topic 1', value: 2},
        {id: 2, title: 'Topic 2', value: 5},
        {id: 3, title: 'Topic 3', value: 1},
        {id: 4, title: 'Topic 4', value: 4},
        {id: 5, title: 'Topic 5', value: 3},
    ]

    <div className="flex flex-col gap-4 w-full p-6 items-center">

    {items.sort((a, b) => b.value - a.value).map((item, index) => (
        <div 
            className="flex gap-2 px-4 items-center h-10 w-full rounded-md text-lg bg-[#ffd700]"
            key={index}
        >
            <div>
                {item.title}
                {item.value}
            </div>
            /5
        </div>
     ))}

    </div>
}

CodePudding user response:

I think this error is due to the fact that you are using ( instead of { in the .map function. The correct syntax of the .map function is:

items.map((item, index) => {
  return <>...</>
})

Your example would work with this:

const items = [
    {id: 1, title: 'Topic 1', value: 2},
    {id: 2, title: 'Topic 2', value: 5},
    {id: 3, title: 'Topic 3', value: 1},
    {id: 4, title: 'Topic 4', value: 4},
    {id: 5, title: 'Topic 5', value: 3},
]

<div className="flex flex-col gap-4 w-full p-6 items-center">

    {items.sort((a, b) => b.value - a.value).map((item, index) => {
        <div 
            className="flex gap-2 px-4 items-center h-10 w-full rounded-md text-lg bg-[#ffd700]"
            key={index}
        >
            <div>
                {item.title}
                {item.value}
            </div>
            /5
        </div>
     })}

</div>
  • Related