Search code examples
sveltestring-concatenationreactive

The reactive variable is not displaying the right output in Svelte


I think it's pretty obvious what this code should do, but the output is not as I expected it to be.

<script>
  let firstName = "first";
  let lastName = "last";
  let myColor = "orange";

  $: fullName = "${firstName} ${lastName}";
  $: console.log(myColor);
</script>

<main>
  <p>{fullName} - and he has a nice {myColor} shirt</p>
  <input type="text" bind:value={firstName} />
  <input type="text" bind:value={lastName} />
  <input type="text" bind:value={myColor} />
</main>

Here is the output (without the input slots):

${firstName} ${lastName} - and he has a nice orange shirt

I don't know why it didn't replace the fullName with the concat vars.


Solution

  • You need to use backticks (template literals) to concatenate strings like that. This works:

    $: fullName = `${firstName} ${lastName}`;