Type void is not assignable to type ReactNode wile rendering a list of items

Viewed 53

I have this piece of code, which would iterate over an object's KVPs and make a list out of them.

import { PersoanaType } from "./PersoanaType";

type Props = {
    persoana: PersoanaType
}

export default function PersoanaDetails(props: Props) {
    return (
        <ul>
            {
                props.persoana &&
                Object.entries(props.persoana).forEach(([key, value], index) => 
                    <li>value</li>
                )
            }
        </ul>
    );
}

Unfortunately, for some reason, I get this error :

Type 'void' is not assignable to type 'ReactNode'.

I can't get why. So, why is this happening and how can I fix it? Thanks!

1 Answers

Use a map instead of forEach as you want to return an array of elements here. Then make sure to add a key to each element in the loop, like so:

import { PersoanaType } from "./PersoanaType";

type Props = {
  persoana: PersoanaType;
};

export default function PersoanaDetails(props: Props) {
  return (
    <ul>
      {props.persoana &&
        Object.entries(props.persoana).map(([key, value], index) => <li key={key}>{value}</li>)}
    </ul>
  );
}
Related