BookmarkButton.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. this.props.crowi.apiGet('/bookmarks.get', {page_id: this.props.pageId})
  14. .then(res => {
  15. if (res.bookmark) {
  16. this.markBookmarked();
  17. }
  18. });
  19. }
  20. handleClick(event) {
  21. event.preventDefault();
  22. const pageId = this.props.pageId;
  23. if (!this.state.bookmarked) {
  24. this.props.crowi.apiPost('/bookmarks.add', {page_id: pageId})
  25. .then(res => {
  26. this.markBookmarked();
  27. });
  28. } else {
  29. this.props.crowi.apiPost('/bookmarks.remove', {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. // if guest user
  43. if (this.props.crowi.me === "") {
  44. return <div></div>;
  45. }
  46. const iconName = this.state.bookmarked ? 'star' : 'star-o';
  47. return (
  48. <a href="#" title="Bookmark" className="bookmark-link" onClick={this.handleClick}>
  49. <Icon name={iconName} />
  50. </a>
  51. );
  52. }
  53. }
  54. BookmarkButton.propTypes = {
  55. pageId: PropTypes.string,
  56. crowi: PropTypes.object.isRequired,
  57. };