Skip to content

Instantly share code, notes, and snippets.

@mbijon
Forked from staylor/yolo.php
Last active Aug 29, 2015
Embed
What would you like to do?
<?php
class React_YOLO {
public function __construct() {
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
}
public function admin_menu() {
add_menu_page( 'React', 'React', 'edit_posts', 'react', array( $this, 'page' ) );
}
public function page() {
wp_enqueue_script( 'wp-api' );
?>
<script src="http://fb.me/react-0.12.1.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.1.js"></script>
<div class="wrap">
<h2>YOLO</h2>
<div id="yolo"></div>
<script type="text/jsx">
var $ = jQuery, YOLO, Post, Posts, Form;
Post = React.createClass({
render: function () {
var post = this.props.data;
return (
<li>{post.id}. {post.title.rendered}</li>
);
}
});
Posts = React.createClass({
render: function () {
var posts = this.props.data.map(function (post) {
return <Post data={post} />;
});
return (
<ul>
{posts}
</ul>
);
}
});
Form = React.createClass({
submit: function (e) {
e.preventDefault();
var title = this.refs.title.getDOMNode(),
content = this.refs.content.getDOMNode();
this.props.onSubmit({
status: 'publish',
title: title.value.trim(),
content: content.value.trim()
});
title.value = '';
content.value = '';
return;
},
render: function () {
return (
<form onSubmit={this.submit}>
<p><input type="text" placeholder="Title" ref="title" /></p>
<p><input type="text" placeholder="Some content..." ref="content" /></p>
<input type="submit" value="Post" />
</form>
);
}
});
YOLO = React.createClass({
getInitialState: function () {
return {posts: []};
},
setPosts: function (data) {
this.setState({posts: data});
},
loadPosts: function () {
$.ajax({
url : '/wp-json/posts'
}).done( _.bind( this.setPosts, this ) );
},
componentDidMount: function () {
this.loadPosts();
},
addPost: function (data) {
var posts = this.state.posts;
posts.pop();
posts.unshift( data );
this.setState({posts: posts});
this.loadPosts();
},
submit: function (data) {
$.ajax({
type: 'post',
url: '/wp-json/posts',
data: {
data: data
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);
}
}).done( _.bind( this.addPost, this ) );
},
render: function() {
return (
<div className="yolo-box">
<Posts data={this.state.posts} />
<Form onSubmit={this.submit} />
</div>
);
}
});
React.render(<YOLO />, document.getElementById('yolo'));
</script>
</div>
<?php
}
}
new React_YOLO();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment