@dwerthen/react-dependency-injection
TypeScript icon, indicating that this package has built-in type declarations

0.0.3 • Public • Published

React dependency injection

This library provides the functionality of dependency injection of React components. For all those times when you want import components during runtime rather than build time.

Basic usage

import React from 'react'
import {
  Dependency,
  DependencyProvider,
} from '@dwerthen/react-dependency-injection'

function MyButton(props: any) {
  return <button style={{ color: 'red' }} {...props} />
}

export default function BasicUsage() {
  return (
    <DependencyProvider Button={MyButton}>
      <Dependency.Button>Click me</Dependency.Button>
    </DependencyProvider>
  )
}

Separate namespaces

If you want to use a separate namespace to encapsulate a set of components, use the function createDependencyContext.

import React from 'react'
import {
  Dependency,
  DependencyProvider,
  createDependencyContext,
} from '@dwerthen/react-dependency-injection'

const {
  Dependency: Dependency2,
  DependencyProvider: DependencyProvider2,
} = createDependencyContext({})

function MyButton(props: any) {
  return <button style={{ color: 'red' }} {...props} />
}
function MyOtherButton(props: any) {
  return <button style={{ color: 'blue' }} {...props} />
}

export default function SeparateNamespace() {
  return (
    <DependencyProvider Button={MyButton}>
      <DependencyProvider2 Button={MyOtherButton}>
        <Dependency.Button>Click me</Dependency.Button>
        <Dependency2.Button>Click me too</Dependency2.Button>
      </DependencyProvider2>
    </DependencyProvider>
  )
}

Dependency Factory

When creating a dependencyContext you can also provide a factory function, which creates dependencies lazily if no matching dependency has been provided.

import React from 'react'
import { createDependencyContext } from '@dwerthen/react-dependency-injection'

const { Dependency, DependencyProvider } = createDependencyContext({
  factory: name => props => <p>This is created component named {name}</p>,
})

export default function DependencyFactory() {
  return (
    <DependencyProvider Button={() => <p>Not factory produced</p>}>
      <Dependency.Button />
      <Dependency.AnotherButton />
      <Dependency.SomeButton />
    </DependencyProvider>
  )
}

Readme

Keywords

none

Package Sidebar

Install

npm i @dwerthen/react-dependency-injection

Weekly Downloads

1

Version

0.0.3

License

MIT

Unpacked Size

10.9 kB

Total Files

6

Last publish

Collaborators

  • dwerthen