0

I have this function:

const getNameListMarkdown = (props: Props) => {
  if (isDefined(props.details)) {
    return (
      Object.keys(props.details).map(x => <p>{props.details![x].name}</p>)
    );
  }

  return '';
};

For some reason, when I then try to render this it is rendered as [object Object], [object Object], for example if I have two objects in the list. If I console log the Object.keys it writes out the strings as it should in the .name space. So it should return a string but it doesn't render as such. And if I check what I get back where I call this function it receives a vNode object where the string can be seen in the children array. Does anyone know how to properly do this?

1
  • 1
    Are you sure you need exclamation point here: details![x] ? Commented Jan 27, 2020 at 9:24

1 Answer 1

3

<p>{props.details![x].name}</p> is JSX. When it is evaluated you get a React element (which is an object), not a string of HTML.

Meanwhile, Array.prototype.map gives you an array. So you end up with an array containing two objects.

When you call (directly or implicitly) .toString() on an array, you get a string made up of each member of the array (hence two "[object Object]"s)


If you want a string, use a template literal instead of JSX:

.map(x => `<p>${props.details![x].name}</p>`)
Sign up to request clarification or add additional context in comments.

1 Comment

what does the ! mean in between details and [x]?

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.