Name: react-simple-di
Owner: Storybook
Description: Deprecated - for bug fixes and maintenance only
Forked from: kadirahq/react-simple-di
Created: 2017-11-15 16:14:44.0
Updated: 2018-05-18 15:55:48.0
Pushed: 2017-12-06 18:43:43.0
Size: 16
Language: JavaScript
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
Simple dependancy injection solution for React.
i react-simple-di
In react-simple-di
, we've two types of dependencies, they are:
Every action will receive the
context
as it's first argument.
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:
t context = {
DB,
Router,
appName: 'My Blog'
t 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:
rt {injectDeps} from 'react-simple-di';
rt Layout from './layout.jsx';
bove mentioned actions and context are defined here.
t LayoutWithDeps = injectDeps(context, actions)(Layout);
Now you can use LayoutWithDeps
anywhere in your app.
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
.
s 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:
rt {useDeps} from 'react-simple-di';
ssume above mentioned CreatePost react component is
efined here.
t depsToPropsMapper = (context, actions) => ({
appName: context.appName,
createPost: actions.posts.create
t 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 byreact-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:
t mapper = (context, actions) => ({
context: () => context,
actions: () => actions