Skip to content

react context #10

@prabirshrestha

Description

@prabirshrestha

Looking at geiger I saw that context are used in an interesting fashion.
https://github.com/netgusto/Geiger

There is also a blog post about react context. https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html (old)

It would be great to document how to use it similar to how the waitFor was documented.

Here is a use case:
Assume you have a widget (component) that would want to share. Let us take twitter feed as an example. It is a pretty complex component so you would want to have a custom store for each instance of the component.

var twitterstore = Hoverboard(TwitterStore);
<Context twitterstore={twitterstore}>
   <TwitterFeed />
</Context>

var TwitterFeed = React.createClass({
   static contextTypes: {
       twitterstore: React.PropTypes.object.isRequired
   },
   componentDidMount() {
      this.twitterstore.getState(state => this.setState({ tweets: tweet }));
   },
    render() {
        return this.state.tweets.map(t => <Tweet tweet={t} />);
    }
};

var Tweet = React.createClass({
   static contextTypes: {
       twitterstore: React.PropTypes.object.isRequired
   },
   onRewteet(e) {
       e.preventDefault();
       this.context.twitterstore.Retweet(this.props.tweet.id);
   },
   render() {
        return <div>{this.props.tweet.text} <input type="button" onClick={this.onRewteet} value="Retweet" /></div>
    }
};

Assume that now the twitterstore is per user. I can now have multiple TwitterFeed component that works independently in the same page.

var userATwitterStore = Hoverboard(TwitterStore);
userATwitterStore.setUserId('A');
<Context twitterstore={userATwitterStore }>
   <TwitterFeed />
</Context>

var userBTwitterStore = Hoverboard(TwitterStore);
userBTwitterStore.setUserId('B');
<Context twitterstore={userBTwitterStore }>
   <TwitterFeed />
</Context>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions