Using Branches

How to use branch components

Overview

Branching components in gt-react enable dynamic content rendering based on specific conditions. These components include:

  • <Branch>: Renders content based on a matching branch prop.
  • <Plural>: Renders content based on pluralization rules for a given number.

Both components provide powerful tools for managing conditional logic and dynamic content in localized applications.

In this guide, we will cover:

What are branch components?

How to use branch components

When to use branch components

Examples

Common pitfalls


What are branch components?

Branch components dynamically choose which content to render based on a specific condition or value.

<Branch>

The <Branch> component allows you to render different content based on a provided branch value. If no matching branch is found, the fallback children content is rendered.

For example, the <Branch> component is perfect for conditional rendering based on application state, user preferences, or any dynamic data.

The most common use case is to use it to replace a ternary or conditional operator.

<Plural>

The <Plural> component extends the functionality of <Branch> by handling pluralization and number agreement automatically. It uses the provided n value to determine which plural form to display, based on locale-specific rules.

For example, the <Plural> component is ideal for rendering singular and plural text dynamically, such as "1 item" vs. "2 items."

Plural components are often combined with <Num> components to localize a number and its corresponding text.

Use with <T>

The <Branch> and <Plural> components should be used within a <T> component to sanitize dynamic content for translation.

When used within a <T> component, the content is automatically translated and rendered in your user's selected language.

When used standalone, they will just render the content as-is, without translating it.


How to use branch components

Branching logic with <Branch>

The <Branch> component is used for flexible content switching based on a branch value.

You can define multiple possible branches, and the component will render the content corresponding to the matching branch key.

Additionally, you can use other variable components in combination with the <Branch> component.

const branch: 'option1' | 'option2' = 'option1';
<T>
  <Branch 
    branch={branch}
    option1={<p>Option 1</p>}
    option2={<p>Option 2</p>}
  >
    Fallback content
  </Branch>
</T>

The <Branch> component should be used within a <T> component. This allows for the content to be automatically translated.

See the API Reference for more details.

Pluralization with <Plural>

The <Plural> component automates pluralization logic based on the value of n. The component dynamically chooses the appropriate plural form for the given number and locale.

const count: number = 1;
<T>
  <Plural
    n={count}
    singular={<><Num>{1}</Num> item.</>}
    plural={<><Num>{count}</Num> items.</>}
    // Additional options
    zero={<><Num>{count}</Num> items.</>}
    one={<><Num>{count}</Num> item.</>}
    two={<><Num>{count}</Num> items.</>}
    few={<><Num>{count}</Num> items.</>}
    many={<><Num>{count}</Num> items.</>}
    other={<><Num>{count}</Num> items.</>}
    dual={<><Num>{count}</Num> items.</>}
  />
</T>

The available plural forms depend on the locale and follow Unicode CLDR pluralization rules.

See the API Reference for more details.


When to use branch components

Branch components are important for managing dynamic content in your application.

When you need to display different content based on a condition, use <Branch>.

These conditions can be based on a variable component, a boolean, or a function.

For example, if your code has a ternary operator or conditional rendering, you can use <Branch> to replace it.

const isActive = true;
// Ternary operator
<Branch branch={isActive} true={<p>The user is active.</p>} false={<p>The user is inactive.</p>}>
  <p>Status unknown.</p>
</Branch>

// Conditional rendering
<Branch branch={isActive} true={<p>The user is active.</p>}>
  <></>
</Branch>
// Ternary operator
const isActive = true;
{isActive ? <p>The user is active.</p> : <p>The user is inactive.</p>}

// Conditional rendering
{isActive && <p>The user is active.</p>}

If you want to render content with correct pluralization, use <Plural>.

const count = 1;
<Plural n={count} one={<p>1 item</p>} other={<p>{count} items</p>} />
const count = 1;
{count === 1 ? <p>1 item</p> : <p>{count} items</p>}

The <Branch> and <Plural> components can be used standalone, without a <T> component. When used standalone, they will just render the content as-is, without translating it.

However, they are often used within a <T> component to sanitize dynamic content for translation.


Examples

<Branch>

import { T, Branch, Var } from 'gt-react';

export default function UserStatus() {
  const [status, setStatus] = useState<'active' | 'inactive' | undefined>(undefined);
  const [name, setName] = useState<string>('John Doe');
  return (
    <T>
      <Branch
        branch={status}
        active={<p>The user <Var>{name}</Var> is active.</p>}
        inactive={<p>The user <Var>{name}</Var> is inactive.</p>}
      >
        <p>Status unknown.</p>
      </Branch>
    </T>
  );
}

In the example above, the <Branch> component dynamically switches between 3 rendered contents based on the value of status.

When status is "active", the component renders:

<p>The user <Var>{name}</Var> is active.</p>

When status is "inactive", the component renders:

<p>The user <Var>{name}</Var> is inactive.</p>

When status is neither "active" nor "inactive", the component renders the fallback content:

<p>Status unknown.</p>

Since the <Branch> component is wrapped in a <T> component, the rendered content is automatically translated in context.

In this example, it displays different descriptions based on the user's subscription plan.

import { Branch } from 'gt-react';

export default function SubscriptionDetails() {
  const [plan, setPlan] = useState<'free' | 'premium' | 'enterprise' | undefined>(undefined);
  return (
    <Branch
      branch={plan}
      free={<p>You are on the Free plan. Upgrade to unlock more features!</p>}
      premium={<p>You are enjoying the Premium plan with full access to features.</p>}
      enterprise={<p>You are on the Enterprise plan. Contact support for tailored solutions.</p>}
    >
      <p>No subscription plan detected.</p>
    </Branch>
  );
}
  • The branch prop determines which plan message to display.
  • If plan is "free", "premium", or "enterprise", the corresponding message is shown.
  • If plan doesn't match any of these values, the fallback content ("No subscription plan detected.") is displayed.

<Plural>

The <Plural> component dynamically handles singular and plural content based on the value of n. This example displays the number of unread messages in a user's inbox.

import { T, Plural, Num } from 'gt-react';

export default function UnreadMessages() {
  const [unreadCount, setUnreadCount] = useState<number>(1);
  return (
    <T>
      <Plural
        n={unreadCount}
        one={<>You have <Num>{unreadCount}</Num> unread message.</>}
        other={<>You have <Num>{unreadCount}</Num> unread messages.</>}
      />
    </T>
  );
}
  • The n prop specifies the number of unread messages.
  • If unreadCount is 1, the component renders: "You have 1 unread message."
  • For any other value, it renders: "You have X unread messages." where X is the value of unreadCount formatted by <Num>.

Common Pitfalls

Missing Branch Values

If a branch value is not provided or does not match any keys, the <Branch> component will render the fallback children content. Always ensure that the possible branch keys match the values passed to the branch prop.

import { Branch } from 'gt-react';

export default function StatusMessage({ status }) {
  return (
    <Branch
      branch={status}
      active={<p>The user is active.</p>}
      inactive={<p>The user is inactive.</p>}
    >
      <p>Status unknown.</p>
    </Branch>
  );
}

If status is undefined or a value other than active or inactive, the fallback content “Status unknown.” will be displayed.

Missing Plural Forms

Remember to specify all necessary plural forms in your default language. This is how gt-react ensures that your application always has fallback content to display.

For example, if English is your default language, you should provide all plural forms for English.

import { Plural, Num } from 'gt-react';

<Plural
  n={count}
  one={<>You have <Num>{count}</Num> unread message.</>}
  other={<>You have <Num>{count}</Num> unread messages.</>}
/>

Here, we have provided one and other plural forms for English.

Alternatively, you can also provide singular and plural for English.


Notes

  • Branch components are essential for managing dynamic and localized content in applications.
  • The <Branch> component is highly flexible and can adapt to various conditions and states.
  • The <Plural> component simplifies pluralization by adhering to locale-specific rules automatically.
  • Always include a fallback children prop for better error handling and user experience.

Next Steps

How is this guide?