1

Why this JSX hook returns [object Object] [object Object] instead of HTML string?

export default function Article (props) {

  const {
    content,
  } = props;

  console.log({content});

  return (
    <>
      <div>
        {content.replace(/<p>(.*?)<\/p>/g, (match) => {
          return (
              <p className="text-black">{match}</p>
          );
        })}
      </div>
    </>
  )
}

Console.log print:

{
  content: '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dignissim ac ante nec hendrerit.</p>\n' +
    '\n' +
    '<p>Morbi rhoncus diam quis sodales iaculis. Morbi ullamcorper consectetur ultricies. Nam vel efficitur erat.</p>'
}

1 Answer 1

3

Issue

Why this JSX hook returns [object Object] [object Object] instead of HTML string?

You are attempting to render the returned of content.replace but the function you use to replace is returning a JSX object instead of a new string. You are also copying the entire match instead of just the captured group.

Solution

It is very unclear to me what you are trying to do, or why, but if you want to modify the raw HTML you can do a string replace, but you need to then use standard HTML (not JSX!!) and set the innerHTML of the div. Here you need to specify class instead of className.

<div
  dangerouslySetInnerHTML={{
    __html: content.replace(/<p>(.*?)<\/p>/g, (match, p1) => {
      return `<p class="text-black">${p1}</p>`;
    })
  }}
></div>

or a bit more simple without the updater function

<div
  dangerouslySetInnerHTML={{
    __html: content.replace(/<p>(.*?)<\/p>/g, '<p class="text-black">$1</p>')
  }}
></div>

Demo

Edit react-js-jsx-returns-object-object-instead-of-string

Sign up to request clarification or add additional context in comments.

Comments

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.