Skip to main content

tagged

The tagged(...tags)(Component, [options]) HoC attaches tags to the component and its child components.

Conditional Bindings are detailed in Conditional Bindings section of the documentation.

Arguments#

tagged(...tags)#

  1. ...tags: Tag[] โ€” tags to be attached to the component.

tagged(...tags)(Component, [isolated])#

  1. Component: React.ComponentType โ€” component to be wrapped.
  2. [options]: TaggedOptions
    • isolated: boolean โ€” by default, the wrapped component and its child components inherit tags from from the upstream tagged components. You can use isolated option to disable this behavior.

Returns#

React.ComponentType โ€” the wrapped component.

Example#

tags.ts
import { tag } from 'brandi';
import { tagged } from 'brandi-react';
export const TAGS = {
offline: tag('offline'),
};
export const withOfflineTag = tagged(TAGS.offline);
index.tsx
import { createContainer } from 'brandi';
import { ContainerProvider } from 'brandi-react';
import React from 'react';
import ReactDOM from 'react-dom';
import { TOKENS } from './tokens';
import { TAGS } from './tags';
import { ApiService, OfflineApiService } from './ApiService';
import { App } from './App';
const container = createContainer();
container
.bind(TOKENS.apiService)
.toInstance(ApiService)
.inTransientScope();
container
.when(TAGS.offline)
.bind(TOKENS.apiService)
.toInstance(OfflineApiService)
.inTransientScope();
ReactDOM.render(
<ContainerProvider container={container}>
<App />
</ContainerProvider>,
document.getElementById('root'),
);
UserComponent.tsx
import { useInjection } from 'brandi-react';
import { FunctionComponent } from 'react';
import { TOKENS } from './tokens';
export const UserComponent: FunctionComponent = () => {
/* โ†“ Will be `ApiService`. */
const apiService = useInjection(TOKENS.apiService);
/* ... */
return (/* ... */);
}
SettingsComponent.tsx
import { useInjection } from 'brandi-react';
import { TOKENS } from './tokens';
import { withOfflineTag } from './tags';
/* โ†“ Tags the component. */
export const SettingsComponent = withOfflineTag(() => {
/* โ†“ Will be `OfflineApiService`. */
const apiService = useInjection(TOKENS.apiService);
/* ... */
return (/* ... */);
});