BookmarkButton.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import React from 'react';
  2. import $ from 'jquery';
  3. export default class BookmarkButton extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. bookmarked: false,
  8. pageId: null,
  9. token: null,
  10. };
  11. this.handleClick = this.handleClick.bind(this);
  12. }
  13. componentWillMount() {
  14. // FIXME(property?)
  15. this.setState({
  16. pageId: $('#content-main').data('page-id'),
  17. token: $('#bookmark-button-react').data('csrftoken'),
  18. });
  19. }
  20. componentDidMount() {
  21. $.get('/_api/bookmarks.get', {page_id: this.state.pageId}, (res) => {
  22. if (res.ok) {
  23. if (res.bookmark) {
  24. this.markBookmarked();
  25. }
  26. }
  27. });
  28. }
  29. handleClick(event) {
  30. event.preventDefault();
  31. const token = this.state.token;
  32. const pageId = this.state.pageId;
  33. if (!this.state.bookmarked) {
  34. $.post('/_api/bookmarks.add', {_csrf: token, page_id: pageId}, (res) => {
  35. if (res.ok && res.bookmark) {
  36. this.markBookmarked();
  37. }
  38. });
  39. } else {
  40. $.post('/_api/bookmarks.remove', {_csrf: token, page_id: pageId}, (res) => {
  41. if (res.ok) {
  42. this.markUnBookmarked();
  43. }
  44. });
  45. }
  46. }
  47. markBookmarked() {
  48. this.setState({bookmarked: true});
  49. }
  50. markUnBookmarked() {
  51. this.setState({bookmarked: false});
  52. }
  53. render() {
  54. const className = this.state.bookmarked ? 'fa fa-star' : 'fa fa-star-o';
  55. return (
  56. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}><i className={className}></i></a>
  57. );
  58. }
  59. }