BookmarkButton.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. };
  9. this.handleClick = this.handleClick.bind(this);
  10. }
  11. componentDidMount() {
  12. this.props.crowi.apiGet('/bookmarks.get', {page_id: this.props.pageId})
  13. .then(res => {
  14. if (res.bookmark) {
  15. this.markBookmarked();
  16. }
  17. });
  18. }
  19. handleClick(event) {
  20. event.preventDefault();
  21. const token = this.props.csrfToken;
  22. const pageId = this.props.pageId;
  23. if (!this.state.bookmarked) {
  24. this.props.crowi.apiPost('/bookmarks.add', {_csrf: token, page_id: pageId})
  25. .then(res => {
  26. this.markBookmarked();
  27. });
  28. } else {
  29. this.props.crowi.apiPost('/bookmarks.remove', {_csrf: token, page_id: pageId})
  30. .then(res => {
  31. this.markUnBookmarked();
  32. });
  33. }
  34. }
  35. markBookmarked() {
  36. this.setState({bookmarked: true});
  37. }
  38. markUnBookmarked() {
  39. this.setState({bookmarked: false});
  40. }
  41. render() {
  42. const iconName = this.state.bookmarked ? 'star' : 'star-o';
  43. return (
  44. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}>
  45. <Icon name={iconName} />
  46. </a>
  47. );
  48. }
  49. }
  50. BookmarkButton.propTypes = {
  51. pageId: React.PropTypes.string,
  52. crowi: React.PropTypes.object.isRequired,
  53. csrfToken: React.PropTypes.string.isRequired,
  54. };