Skip to content

universal-di/react

Repository files navigation

Universal Dependency Injection port for React

MIT License Build Status NPM version Coverage Status PRs welcome

Pre-requisites

Contents

Before you inject

Before you can inject anything, you need to create a module and register your dependencies. You can do this in a separate file or in the same file as your React component.

If you haven't already, install the Universal Dependency Injection package:

npm install @universal-di/core

...and create a module:

const MY_TOKEN = new InjectionToken<string>("MY_TOKEN");

@Module({
    providers: [{ provide: MY_TOKEN, useValue: "Hello world" }],
})
class AppModule {}

DIContextProvider

DIContextProvider is a React context provider that allows you to provide dependencies to your React DOM.

const application = new DIApplication(AppModule);

<DIContextProvider injector={application.rootInjector}>
    <ProductListComponent />
</DIContextProvider>;

useInjection

useInjection is a hook that allows you to inject dependencies into your React components.

export function ProductListComponent() {
    // MY_TOKEN type is inferred here
    const injectedString = useInjection(MY_TOKEN);

    useEffect(() => {
        console.log(injectedString);
    }, []);
}

Authors

szymeo bartoszswitalski

About

Universal Dependency Injection port for React

Resources

License

Stars

Watchers

Forks

Packages

No packages published