BookmarkButton.js 1.4 KB

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