BookmarkButton.js 1.6 KB

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