BookmarkButton.js 1.5 KB

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