liveBook · Manning

Directive

As explained in Build a Frontend Web Framework (From Scratch)

A framework-specific instruction attached to markup that changes the behavior, rendering, or processing of an element.

A directive is a framework-specific instruction in an HTML template that adds or changes a DOM element’s behavior. Common uses include displaying elements conditionally and iterating over arrays. section 1.3.1

Vue’s v-if is a custom directive: it shows an element when application state permits. Svelte and React express the same conditional behavior with different syntaxes. section 1.3.1

Recognize the main responsibilities of directives:

  • Attach framework behavior to markup. section 1.3.1
  • Render or hide elements from application state. section 1.3.1
  • Represent framework-specific alternatives to comparable template or JSX expressions. section 1.3.1
<p v-if="hasDiscount">
  You get a discount!
</p>

Inspect the Vue conditional directive in a focused template example. section 1.3.1

{#if hasDiscount}
<p>
  You get a discount!
</p>
{/if}

Compare Svelte’s block syntax for the same conditional rendering behavior. section 1.3.1

{hasDiscount && <p>You get a discount!</p>}

Compare React’s JSX expression for state-dependent rendering. section 1.3.1

How Build a Frontend Web Framework (From Scratch) covers it

How deep it goes
Defines conditional display and array iteration but stops short of implementing directive processing.
Examples
Uses Vue v-if, a Svelte if block, and a React JSX conditional expression.
What it assumes
Assumes familiarity with HTML templates, DOM elements, and application state.
What you can do after
Evaluate how frameworks express state-dependent element rendering in templates or JSX.
How it connects
Connects directives with HTML templates, DOM elements, application state, conditional rendering, array iteration, and JSX.

Also explained in

Compare how 3 books explain directive →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Frontend Web Framework (From Scratch). The section links point to the parts of the book it draws on.