Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template string in React

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.

like image 978
DragoJokera Avatar asked Oct 28 '25 04:10

DragoJokera


2 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>
like image 76
Quentin Avatar answered Oct 30 '25 12:10

Quentin


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>
like image 38
CertainPerformance Avatar answered Oct 30 '25 12:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!