Skip to content

Instantly share code, notes, and snippets.

@AlexFrazer
Created June 27, 2017 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexFrazer/c0594e29cc21bb69894cbec211e11de4 to your computer and use it in GitHub Desktop.
Save AlexFrazer/c0594e29cc21bb69894cbec211e11de4 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import DevTools from 'mobx-react-devtools';
@observer
export default class App extends Component {
state = {
value: '',
};
onSubmit = (e) => {
e.preventDefault();
console.log(this.props);
const { appState: { posts: { addPost } } } = this.props;
addPost({ title: this.state.value });
this.input.value = '';
};
onChange = ({ target: { value } }) => this.setState({ value });
input = null;
renderPosts() {
const { appState: { posts: { posts } } } = this.props;
return posts.map(({ body, title }) => (
<div>
<h1>{title}</h1>
<p>{body}</p>
</div>
))
}
render() {
const { appState: { posts: { posts } } } = this.props;
return (
<div>
<h1>Hello</h1>
<div>You have {posts.length} posts</div>
<form onSubmit={this.onSubmit}>
<input
type="text"
onChange={this.onChange}
ref={e => { this.input = e; }}
/>
</form>
{this.renderPosts()}
<DevTools />
</div>
);
}
}
// app/AppState.js
import { observable } from 'mobx';
import PostsStore from 'app/stores/PostsStore';
export default class AppState {
posts = new PostsStore();
}
// app/index.jsx
import React from 'react';
import AppState from 'app/AppState';
const appState = new AppState();
async function bootstrap(Component: React.Component<any>) {
const { render } = await import('react-dom');
const { AppContainer } = await import('react-hot-loader');
const target = document.getElementById('root');
render(
<AppContainer>
<Component appState={appState} />
</AppContainer>,
target
);
}
import('app/components/Root')
.then(({ default: Root }) => bootstrap(Root));
if (module.hot) {
module.hot.accept('app/components/Root', async () => {
const { default: NextRoot } = await import('app/components/Root');
bootstrap(NextRoot);
});
}
// app/stores/PostsStore.js
import { observable } from 'mobx';
export default class PostsStore {
@observable posts = [];
addPost = ({ title = '[Untitled]', body = '' }) => {
this.posts.push({
title,
body,
createdAt: Date.now(),
});
}
}
import React from 'react';
import App from 'app/components/App';
export default function Root({ appState }) {
return (<App appState={appState} />);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment