GithubHelp home page GithubHelp logo

react-simple-di's Introduction

react-simple-di

Simple dependancy injection solution for React.

Installation

npm i react-simple-di

Intro

In react-simple-di, we've two types of dependencies, they are:

  1. context - These are usually, configurations, models and client for different remote data solutions.
  2. actions - Actions are simple functions which used to perform business logic with the help of the above context.

Every action will receive the context as it's first argument.

Injecting Dependancies

First, we need to inject dependencies to a root level React component. Mostly, this will be the main layout component of our app.

Here are our dependencies:

const context = {
    DB,
    Router,
    appName: 'My Blog'
};

const actions = {
    posts: {
        create({DB, Router}, title, content) {
            const id = String(Math.random());
            DB.createPost(id, title, content);
            Router.go(`/post/${id}`);
        }
    }
};

First we've defined our context. Then, we have our actions. Here actions must follow a structure like mentioned above.

Let's inject our dependencies:

import {injectDeps} from 'react-simple-di';
import Layout from './layout.jsx';

// Above mentioned actions and context are defined here.

const LayoutWithDeps = injectDeps(context, actions)(Layout);

Now you can use LayoutWithDeps anywhere in your app.

Using Depedencies

Any component rendered inside LayoutWithDeps can access both context and actions.

When using dependecies it will compose a new React component and pass dependencies via props to the original component.

First let's create our UI component. Here it will expect dependecies to come via props appName and createPost.

class CreatePost extends React.Component {
    render() {
        const {appName} = this.props;
        return (
            <div>
                Create a blog post on app: ${appName}. <br/>
                <button onClick={this.create.bind(this)}>Create Now</button>
            </div>
        );
    }

    create() {
        const {createPost} = this.props;
        createPost('My Blog Title', 'Some Content');
    }
}

So, let's use dependencies:

import {useDeps} from 'react-simple-di';

// Assume above mentioned CreatePost react component is
// defined here.

const depsToPropsMapper = (context, actions) => ({
    appName: context.appName,
    createPost: actions.posts.create
});

const CreatePostWithDeps = useDeps(depsToPropsMapper)(CreatePost);

That's it.

Note: Here when calling the actions.posts.create action, you don't need to provide the context as the first argument. It'll handle by react-simple-di.

Default Mapper

If you didn't provide a mapper function, useDeps will use a default mapper function will allows you to get context and props directy. Here's that default mapper:

const mapper = (context, actions) => ({
    context: () => context,
    actions: () => actions
});

react-simple-di's People

Contributors

arunoda avatar superandrew213 avatar zvictor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-simple-di's Issues

Is this package still maintained?

I see some things not very update to date with the last versions of React.

Is this still maintained?

Is people moving away from it?

Support nested actions

Hi,

I have a large app and find it beneficial to sometimes categorise the actions in my Mantra modules:

posts.list.created
posts.list.deleted
posts.admin.edit
// etc...

Possible implementation:

export function injectDeps(context, _actions) {
  const actions = {};

  function bindNested (obj) {
      var memo = {};
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === 'object') {
            memo[key] = bindNested(obj[key]);
          } else {
            memo[key] = obj[key].bind(null, context);
          }
        }
      }
      return memo;
    }

    for (var key in _actions) {
      if (_actions.hasOwnProperty(key)) {
        var actionMap = _actions[key];
        var newActionMap = {};
        for (var actionName in actionMap) {
          if (actionMap.hasOwnProperty(actionName)) {
            var actionOrObj = actionMap[actionName];
            if (typeof actionOrObj === 'object') {
              newActionMap[actionName] = bindNested(actionOrObj);
            } else {
              newActionMap[actionName] = actionOrObj.bind(null, context);
            }
          }
        }
        actions[key] = newActionMap;
      }
    }
  // etc...

Let me know if you'd accept a PR for this :)

pass props to mapper

is it possible to pass props to mapper?

export const mapper = (context, actions) => {
  // how to access props from component?
  return {
    context: () => context,
    actions: () => actions
  }
};

mapped props should not override component props

currently mapped props will always override any property passed:


        const newProps = {
          ...this.props,
          ...mappedProps
        };

This makes it impossible to override such a property.

Switching it the other way around would make it more flexible:


        const newProps = {
          ...mappedProps
          ...this.props,
        };

Dependancy Injection error when multiple call injectDeps()

when i make multiple layout like this

const MainLayoutCtx = injectDeps(context, actions)(MainLayout);
const OrgChartLayoutCtx = injectDeps(context, actions)(OrgChartLayout);

the method within actions will have tow context parameters like this

actions: {
  posts: {
    create(context, context, title, comment) {
      // the second parameter also context !
    }
  }
}

if i call injectDeps three times, it will be three context injected

actions: {
  posts: {
    create(context, context, context, title, comment) {
      // the second and third parameter also context !
    }
  }
}

default mapper with functions

Why default mapper looks like this:

const defaultMapper = (context, actions) => ({
  context: () => context,
  actions: () => actions
});

"with functions" and not just like this:

const defaultMapper = (context, actions) => ({
  context: context,
  actions: actions
});

?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.