Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
dist/
node_modules/
test-harness/
package-lock.json
CHANGELOG.md
78 changes: 76 additions & 2 deletions packages/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ In addition to the feature provided by the [web sdk](https://openfeature.dev/doc
- [Usage](#usage)
- [OpenFeatureProvider context provider](#openfeatureprovider-context-provider)
- [Evaluation hooks](#evaluation-hooks)
- [Declarative components](#declarative-components)
- [FeatureFlag Component](#featureflag-component)
- [Multiple Providers and Domains](#multiple-providers-and-domains)
- [Re-rendering with Context Changes](#re-rendering-with-context-changes)
- [Re-rendering with Flag Configuration Changes](#re-rendering-with-flag-configuration-changes)
Expand Down Expand Up @@ -166,6 +168,68 @@ import { useBooleanFlagDetails } from '@openfeature/react-sdk';
const { value, variant, reason, flagMetadata } = useBooleanFlagDetails('new-message', false);
```

#### Declarative components

The React SDK includes declarative components for feature flagging that provide a more JSX-native approach to conditional rendering.

##### FeatureFlag Component

The `FeatureFlag` component conditionally renders its children based on feature flag evaluation:

```tsx
import { FeatureFlag } from '@openfeature/react-sdk';

function App() {
return (
<OpenFeatureProvider>
{/* Basic usage - renders children when flag is truthy */}
<FeatureFlag flagKey="new-feature" defaultValue={false}>
<NewFeatureComponent />
</FeatureFlag>

{/* Match specific values */}
<FeatureFlag flagKey="theme" match="dark" defaultValue="light">
<DarkThemeStyles />
</FeatureFlag>

{/* Boolean flag with fallback */}
<FeatureFlag flagKey="premium-feature" match={true} defaultValue={false} fallback={<UpgradePrompt />}>
<PremiumContent />
</FeatureFlag>

{/* Custom predicate function for complex matching */}
<FeatureFlag
flagKey="user-segment"
defaultValue=""
match="beta"
// check if the actual flag value includes the match ('beta')
predicate={(expected, actual) => !!expected && actual.value.includes(expected)}
>
<BetaFeatures />
</FeatureFlag>

{/* Function as children for accessing flag details */}
<FeatureFlag flagKey="experiment" defaultValue="control" match="beta">
{({ value, reason }) => (
<span>
value is {value}, reason is {reason?.toString()}
</span>
)}
</FeatureFlag>
</OpenFeatureProvider>
);
}
```

The `FeatureFlag` component supports the following props:

- **`flagKey`** (required): The feature flag key to evaluate
- **`defaultValue`** (required): Default value when the flag is not available
- **`match`** (optional): Value to match against the flag value. By default, strict equality (===) is used for comparison
- **`predicate`** (optional): Custom function for matching logic that receives the expected value and evaluation details
- **`children`**: Content to render when condition is met (can be JSX or a function receiving flag details)
- **`fallback`** (optional): Content to render when condition is not met

#### Multiple Providers and Domains

Multiple providers can be used by passing a `domain` to the `OpenFeatureProvider`:
Expand Down Expand Up @@ -308,8 +372,8 @@ The [OpenFeature debounce hook](https://github.com/open-feature/js-sdk-contrib/t
### Testing

The React SDK includes a built-in context provider for testing.
This allows you to easily test components that use evaluation hooks, such as `useFlag`.
If you try to test a component (in this case, `MyComponent`) which uses an evaluation hook, you might see an error message like:
This allows you to easily test components that use evaluation hooks (such as `useFlag`) or declarative components (such as `FeatureFlag`).
If you try to test a component (in this case, `MyComponent`) which uses feature flags, you might see an error message like:

> No OpenFeature client available - components using OpenFeature must be wrapped with an `<OpenFeatureProvider>`.

Expand All @@ -330,6 +394,16 @@ If you'd like to control the values returned by the evaluation hooks, you can pa
<OpenFeatureTestProvider flagValueMap={{ 'my-boolean-flag': true }}>
<MyComponent />
</OpenFeatureTestProvider>

// testing declarative FeatureFlag components
<OpenFeatureTestProvider flagValueMap={{ 'new-feature': true, 'theme': 'dark' }}>
<FeatureFlag flagKey="new-feature" defaultValue={false}>
<NewFeature />
</FeatureFlag>
<FeatureFlag flagKey="theme" match="dark" defaultValue="light">
<DarkMode />
</FeatureFlag>
</OpenFeatureTestProvider>
```

Additionally, you can pass an artificial delay for the provider startup to test your suspense boundaries or loaders/spinners impacted by feature flags:
Expand Down
124 changes: 124 additions & 0 deletions packages/react/src/declarative/FeatureFlag.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import React from 'react';
import { useFlag } from '../evaluation';
import type { FlagQuery } from '../query';
import type { FlagValue, EvaluationDetails } from '@openfeature/core';
import { isEqual } from '../internal';

/**
* Default predicate function that checks if the expected value equals the actual flag value.
* @param {T} expected The expected value to match against
* @param {EvaluationDetails<T>} actual The evaluation details containing the actual flag value
* @returns {boolean} true if the values match, false otherwise
*/
function equals<T extends FlagValue>(expected: T, actual: EvaluationDetails<T>): boolean {
return isEqual(expected, actual.value);
}

/**
* Props for the FeatureFlag component that conditionally renders content based on feature flag state.
* @interface FeatureFlagProps
*/
interface FeatureFlagProps<T extends FlagValue = FlagValue> {
/**
* The key of the feature flag to evaluate.
*/
flagKey: string;

/**
* Optional predicate function for custom matching logic.
* If provided, this function will be used instead of the default equality check.
* @param expected The expected value (from match prop)
* @param actual The evaluation details
* @returns true if the condition is met, false otherwise
*/
predicate?: (expected: T | undefined, actual: EvaluationDetails<T>) => boolean;

/**
* Content to render when the feature flag condition is met.
* Can be a React node or a function that receives flag query details and returns a React node.
*/
children: React.ReactNode | ((details: FlagQuery<T>) => React.ReactNode);

/**
* Optional content to render when the feature flag condition is not met.
* Can be a React node or a function that receives evaluation details and returns a React node.
*/
fallback?: React.ReactNode | ((details: EvaluationDetails<T>) => React.ReactNode);
}

/**
* Configuration for matching flag values.
* For boolean flags, `match` is optional (defaults to checking truthiness).
* For non-boolean flags (string, number, object), `match` is required to determine when to render.
*/
type FeatureFlagMatchConfig<T extends FlagValue> = {
/**
* Default value to use when the feature flag is not found.
*/
defaultValue: T;
} & (T extends boolean
? {
/**
* Optional value to match against the feature flag value.
*/
match?: T | undefined;
}
: {
/**
* Value to match against the feature flag value.
* Required for non-boolean flags to determine when children should render.
* By default, strict equality is used for comparison.
*/
match: T;
});
Comment on lines +60 to +73
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be a little more intuitive if the name of the expected value param would be the same for this and for the predicate.
I am leaning a bit more towards expected than match.

Copy link
Member

@toddbaert toddbaert Dec 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it would be great if these names were consistent.

However, I'm not 100% sure about "expect"/"expected", especially in JS, this to me strongly implies testing, which I feel like brings in conceptual baggage.

I wonder if going the other way is better, and changing the predicate...

from:

  /**
   * Optional predicate function for custom matching logic.
   * If provided, this function will be used instead of the default equality check.
   * @param expected The expected value (from match prop)
   * @param actual The evaluation details
   * @returns true if the condition is met, false otherwise
   */
  predicate?: (expected: T | undefined, actual: EvaluationDetails<T>) => boolean;

to:

  /**
   * Optional predicate function for custom matching logic.
   * If provided, this function will be used instead of the default equality check.
   * @param match The expected value (from match prop)
   * @param details The evaluation details
   * @returns true if the condition is met, false otherwise
   */
  predicate?: (match: T | undefined, details: EvaluationDetails<T>) => boolean;

This is very plain/simple... the names are just what they are - the match prop you specified, and the evaluation details.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps matchValue would be even better for both, since it's specifically the value of the details we are matching.

Copy link

@marcozabel marcozabel Dec 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @toddbaert that "match" is more fitting, as "expected" tends to carry a testing connotation, which doesn’t align with the context of feature flags where there’s no predefined expectation of a value.


type FeatureFlagComponentProps<T extends FlagValue> = FeatureFlagProps<T> & FeatureFlagMatchConfig<T>;

/**
* @experimental This API is experimental, and is subject to change.
* FeatureFlag component that conditionally renders its children based on the evaluation of a feature flag.
* @param {FeatureFlagComponentProps} props The properties for the FeatureFlag component.
* @returns {React.ReactElement | null} The rendered component or null if the feature is not enabled.
*/
export function FeatureFlag<T extends FlagValue = FlagValue>({
flagKey,
match,
predicate,
defaultValue,
children,
fallback = null,
}: FeatureFlagComponentProps<T>): React.ReactElement | null {
const details = useFlag(flagKey, defaultValue, {
updateOnContextChanged: true,
});

// If the flag evaluation failed, we render the fallback
if (details.reason === 'ERROR') {
const fallbackNode: React.ReactNode =
typeof fallback === 'function' ? fallback(details.details as EvaluationDetails<T>) : fallback;
return <>{fallbackNode}</>;
}

// Use custom predicate if provided, otherwise use default matching logic
let shouldRender = false;
if (predicate) {
shouldRender = predicate(match as T, details.details as EvaluationDetails<T>);
} else if (match !== undefined) {
// Default behavior: check if match value equals flag value
shouldRender = equals(match, details.details as EvaluationDetails<T>);
} else if (details.type === 'boolean') {
// If no match value is provided, render if flag is truthy
shouldRender = Boolean(details.value);
} else {
shouldRender = false;
}

if (shouldRender) {
const childNode: React.ReactNode = typeof children === 'function' ? children(details as FlagQuery<T>) : children;
return <>{childNode}</>;
}

const fallbackNode: React.ReactNode =
typeof fallback === 'function' ? fallback(details.details as EvaluationDetails<T>) : fallback;
return <>{fallbackNode}</>;
}
1 change: 1 addition & 0 deletions packages/react/src/declarative/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './FeatureFlag';
1 change: 1 addition & 0 deletions packages/react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './declarative';
export * from './evaluation';
export * from './query';
export * from './provider';
Expand Down
Loading