Search code examples
reactjsprop

how make [Object object] to string in react


Question:
export function Main () {

return (
  <div className="py-4">
  <Discount/>
  <Text
  subtitle={`
  ${JSON.stringify(`${<h1>Some <p className="class">generation</p> here</h1>}` )}
  `}/>
  </div>
)
}

I want output text as in image (when some text have class)
img

I use react js
MVP:https://codesandbox.io/s/props-modificator-7nt43o?file=/src/App.js JSON.parse doesn't helps JSON.stringify doesn't helps

There are 3 solutions

 export function Main () {
  
  const subtitleHtml = `Some <p class='text-gradient'>solution2</p> here`;


return (
  <div className="py-4">
  <Discount/>
  <Text

  title={<div className="flex flex-row gap-1.5">Some<p class='text-gradient'>solution1</p> here</div>}

subtitle={<div className="flex flex-row gap-1" 
dangerouslySetInnerHTML={{ __html: subtitleHtml }} />}

//I find this the best one cause you can wrap {solution3} in any <tag>
solution3={
          <h1 class="text-7xl font-bold">
            The Next
            <span class="text-gradient"> solution 3 </span>
            Payment method.
          </h1>
        }
      />
      </div>
    )
    }

Solutions MVP - https://codesandbox.io/s/props-modificator-forked-dnxmnu?file=/src/App.js


Solution

  • You take a JSX object

    <h1>Some <p className="class">generation</p> here</h1>
    

    and stringify it

    `${<h1>Some <p className="class">generation</p> here</h1>}`
    

    that's where you get your [object Object] string.

    Then you JSON.stringify('[object Object]') which gives you another string: '"[object Object]"'.

    Then you take this string and wrap it into yet another string:

    subtitle={`
      ${'"[object Object]"'}
      `}
    

    ain't that a bit overkill?

    If you want to pass the <h1>...</h1> to the <Text /> then just do so:

    return (
      <div className="py-4">
        <Discount/>
        <Text subtitle={<h1>Some <p className="class">generation</p> here</h1>} />
      </div>
    );