React Yield


Ember has a powerful concept of yielding values to children. This is a way to pass values from a parent component to a child component. This is useful when you want to pass values to a the contents of the children when composed. Importantly it is flexible, allowing the child to access the values, or not.

This utility is a way to mimic the behavior of yield in React.

In ember, we have the ability to yield a value to the children. Done like so:

import Component from '@glimmer/component';

export default class AnExample extends Component {
	get value() {
    return {
      someValue: 'some value',
    };
	}

	<template>
        <div>
            {{yield this.value}}
        </div>
	</template>
}

When used, it allows the child to access the values, or not, depending on the implementation:

With values

<AnExample as |value|>
    {{value.someValue}}
    <div>Some other content</div>
</AnExample>

Without values

<AnExample>
    No values
    <div>Some other content</div>
</AnExample>

In React, there is no built-in way to yield values to children natively. To solve for this we created this Yield component which mimics the behavior:

import React from 'react';
import { Yield } from '../../../-private/components/yield/react';
import type { YieldChildren } from '../../../-private/components/yield/react';

type YieldValue = {
    someValue: string;
}

type Props = {
    children: YieldChildren<YieldValue>;
}

export default function AnExample({ children }: Props) {
  const value = {
    someValue: 'some value'
  }

  return (
    <div>
      <Yield props={value}>{children}</Yield>
    </div>
  );
}

With values

<AnExample>
  {({ someValue }) => <div>{someValue}</div>}
  <div>Some other content</div>
</AnExample>

Without values

<AnExample>
  No values
  <div>Some other content</div>
</AnExample>

API

Yield

The Yield component is a way to yield values to children.

Props

  • props: The value to yield to the children.
  • children: The children to render. This can be a function that receives the yielded values, or not.
<Yield props={value}>{children}</Yield>

YieldChildren

The YieldChildren type is a way to type the children of the Yield component. Should be used to type the children of the component that uses the Yield component.

type YieldValue = {
    someValue: string;
}

type Props = {
    children: YieldChildren<YieldValue>;
}