Template string in React

Viewed 1583

I got the following code:

export default function CancelledPayment() {

  const linkPage = <Link to="/dashboard/payment" className={clsx(classes.paymentLinkTypography, classes.link)}> here </Link>;

  return (
    <Container>
      <Paper >
        <Paper />
        <Typography>
          {` To go back to your order please click ${linkPage}.You will be redirect in ${count} seconds.`}
        </Typography>
      </Paper>
    </Container>
  );
}

Any idea why is it returning linkPage as [object Object]? The counter is correct, everything is working fine just this linkPage is not okay. If I took it out like:

To go back to your order please click {linkPage}. {`You will be redirect in ${count} seconds.`}

it is working fine, also in some other cases, but I would like everything to be in one line, using template string.

3 Answers

Template strings are a tool to create strings.

JSX is a tool to generate DOM(ish) objects.

When you force an object into a string you get "[object Object]" and not some JSX source code.

Don't use a template string for this. JSX is all you need.

    <Typography>
      To go back to your order please click {linkPage}.
     You will be redirect in {count} seconds.
    </Typography>

Template strings are only for plain string interpolation with JavaScript. They always evaluate to a string. In contrast, using JSX to render React children allows for the interpolation of React elements.

You get [object Object] because

` To go back to your order please click ${linkPage}.

linkPage is a React child, which is a plain object - when coerced to a string, [object Object] is the result. Template literals always evaluate to strings, nothing else - they can't store React children.

So, you need something like:

<Typography>
{
    'To go back to your order please click'
    {linkPage}
    '. You will be redirected in'
    {count}
    'seconds.'
}
</Typography>

javascript is calling toString for any variable you're passing in the template string. And for any object calling toString will return [object Object] as value.

In your case what you want is something like:

<Typography>
  {'To go back to your order please click'}
  {linkPage}
  {`linkPage.You will be redirect in ${count} seconds.`}
</Typography>
Related