Conditional Rendering
Dynamically render content in diagrams based on conditional logic.
Conditional rendering in Neural Sketch enables diagrams to dynamically adapt based on logical conditions, enhancing flexibility and expressiveness. Built on robust layer constructs and syntax, it provides a reliable and efficient system for conditional evaluation and rendering.
This powerful mechanism lets you render specific diagram elements conditionally, simplifying the creation of diagrams that adjust to various states or inputs.
Overview
Conditional rendering in Neural Sketch is primarily managed through two macros:
\nskSwitch
: Defines a conditional context.\nskCase
and\nskDefault
: Handle specific cases within this context.
Each switch evaluates an expression against defined cases, rendering content accordingly.
Syntax
Here's the general structure:
<type>
can beint
,string
,float
, orbool
.<value>
is the expression evaluated by the switch.<case-value>
defines individual cases to match against<value>
.
Examples
Basic Example
The following example illustrates conditional rendering for different data types:
Conditional Diagram Components
Conditional rendering integrates seamlessly within diagrams, dynamically altering visual components based on conditions:
Best Practices
- Clear cases: Clearly define each case with descriptive names or values.
- Default cases: Always include a default case to handle unexpected conditions gracefully.
- Type consistency: Ensure the
type
matches the evaluated value and case values to avoid mismatches.
Using Conditional Rendering as If-Else
You can easily replicate simple if-else
logic by providing only one case and the default. This structure behaves exactly like an if-else
statement:
This approach simplifies scenarios that only require binary (yes/no, true/false) decision-making.
Advanced Usage
You can nest conditional switches for more complex diagrams, enabling multi-level conditional rendering:
This example demonstrates conditional rendering within nested contexts, enabling sophisticated diagram logic.
Reference
Prop | Type | Default |
---|---|---|
type? | choice | string |
Key Takeaway
Conditional rendering significantly enhances diagram flexibility, allowing you to build dynamic, responsive, and adaptable visuals with ease.