Tutorial

Using if Blocks in Svelte

Published on September 10, 2019
    Using if Blocks in Svelte

    In this tutorial, we’ll see how to use the if blocks with the Svelte framework to add some flow control logic to our Svelte markup code.

    Blocks in Svelte start use the {#block}...{/block} syntax, so if blocks use the {#if}...{/if} syntax. And, as you’ll see, we can also add an else block and/or elseif blocks as part of an if block.

    Let’s start with the simplest example where we only show some markup if the lightsOn prop passed-in evaluates to true:

    SomeComponent.svelte
    <script>
      export let lightsOn;
    </script>
    
    {#if lightsOn}
      <p>I can see clearly now!</p>
    {/if}
    

    We can also add an else block using the {:else} syntax:

    SomeComponent.svelte
    <script>
      export let lightsOn;
    </script>
    
    {#if lightsOn}
      <p>I can see clearly now!</p>
    {:else}
      <p>It's too dark in here! 🌑</p>
    {/if}
    

    elseif

    We can also add any number of elseif blocks with the {:else if condition} syntax. Let’s modify our example a little:

    SomeComponent.svelte
    <script>
      export let pickedColor;
    </script>
    
    {#if pickedColor === 'green'}
      <p>I agree with you! 💚</p>
    {:else if pickedColor === 'blue'}
      <p>Even better! 💙</p>
    {:else if pickedColor === 'purple'}
      <p>Ok then! 💜</p>
    {/if}
    

    And in the above example we could have also added an else block as the last item in our if block to add some markup if none of our conditions have been true.


    Next let’s go over a simple app example that uses an if block to hide or display some markup. The example will also be a good reminder on how to initialize a new Svelte project.

    Feel free to skip that part if you feel like you now have a good grasp over setting up a Svelte project and using if blocks.

    Example App

    To help illustrate and hammer-in the knowledge around if blocks, we’ll create a small and simple QR code generator app with the help of this QR code generator API.

    So, let’s start our journey with this mini project 🚣‍.

    Project Setup

    • Install the recommended version of the Node if you don’t have one.
    • Create a folder for the new project

    Now open your terminal and type the below commands:

    $ npx degit sveltejs/template qr-code-generator
    $ cd qr-code-generator
    $ npm install
    

    Now to see whether you setup your project correctly or not run the below command: 🙈

    $ npm run dev
    

    Now open localhost:5000 in your browser.

    It should look something like this:

    View after setting up svelte project

    Your file structure will look something like this.

    qr-code-generator
      |- node_modules  
      |- index.js
      |- public
      |- src
        |- App.svelte
        |- main.js
    

    Open App.svelte. this is the main file where we’ll write our code. Start by deleting all its content.

    Start Building the Project

    HTML and CSS parts

    Let’s first start with the HTML markup part and making a small form to submit the text entered for which you have to generate the QR Code.

    App.svelte
    <div class="wrapper">
      <h1>QR CODE GENERATOR</h1>
      <form on:submit|preventDefault={dataSubmit}>
        <input bind:value={inputText}
                class="textInput"
                type="text"
                placeholder="Enter any text or url..." />
        <input class="btn" type="submit" value="Submit" />
      </form>
    </div>
    

    Here, dataSubmit is a function we’ll later in the JavaScript part. on:submit is similar to the native onsubmit() and is used as the event handler for the form’s submit event. Notice how we’ve also used the preventDefault modifier to avoid having to add extra boilerplate code to our handler function.

    bind:value={inputText} is for two-way binding between the value of the input and the inputText variable.

    You can also write the CSS on the same App.svelte file using a style tag:

    App.svelte
    .wrapper {
      max-width: 700px;
      margin: 0 auto;
    }
    
    .textInput {
      width: 70%;
      height: 40px;
      color: #484848;
      border-width: 1.5px;
      border-style: solid;
      border-color: black;
      padding: 3px;
      font-weight: 700;
    }
    
    .btn {
      border-radius: 3px;
      background-color: black;
      color: whitesmoke;
      font-weight: 700;
      cursor: pointer;
    }
    

    After writing the above code, the page will look something like this:

    View after writing some html

    Scripting Part

    In the same App.svelte file you can write the JavaScript part also using a script tag.

    Initialize the QR server API with the variable and also initialize the above-used variables inside the script tag. The dataSubmit() function should also be defined there.

    App.svelte
    <script>
    let inputText = "";
    let API_URL = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=";
    function dataSubmit(e) {
      // logic will go here
    }
    </script>
    

    Next let’s create a variable which indicates whether or not text is entered by the user and start writing the logic for the QR code:

    App.svelte
    <script>
    let inputText = "";
    let textPresent = false;
    let API_URL = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=";
    function dataSubmit(e) {
      if (inputText !== "") {
        textPresent = true;
        API_URL += inputText;
      }
    }
    </script>
    

    Enter if Blocks

    Now we have to add some HTML and the if block part to show the generated QR code when text is entered:

    App.svelte
    <div  class="wrapper">
      <h1>QR CODE GENERATOR</h1>
      <form on:submit={dataSubmit}>
        <input class="textInput"
               type="text"
               placeholder="Enter any text or url..."
               bind:value={inputText} />
        <input class="btn" type="submit" value="Submit" />
      </form>
    
      {#if textPresent}
        <img src={API_URL} /><br>
        <a href={API_URL} download>Download</a> 
      {/if}
    </div>
    

    If textPresent is true then the markup inside the if block will be visible and included in the DOM.

    else Block

    You can also use an else block to display something else if the condition of the if statement doesn’t evaluate to true:

    <div  class="wrapper">
      <h1>QR CODE GENERATOR</h1>
      <form on:submit={dataSubmit}>
        <input class="textInput"
               type="text"
               placeholder="Enter any text or url..."
               bind:value={inputText} />
        <input class="btn" type="submit" value="Submit" />
      </form>
    
      {#if textPresent}
        <img src={API_URL} /><br>
        <a href={API_URL} download>Download</a> 
      {:else}
        <p>No QR code yet! ☹️</p>
      {/if}
    </div>
    

    Now add a little bit more styling: 🤓

    App.svelte
    img {
      margin-top: 100px;
      margin-bottom: 30px;
    }
    
    a {
      font-weight: 700px;
      font-size: 30px;
      color: black;
    }
    

    Now on entering some text in the input box and clicking submit you will get the QR code representing that text.

    Something like this 😍.

    Generated QR Code of alligator.io

    Your app is now ready for production! 🥳🔥

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about our products

    About the authors

    While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    This textbox defaults to using Markdown to format your answer.

    You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Featured on Community

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more