BookmarkButton.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. 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: PropTypes.string,
  52. crowi: PropTypes.object.isRequired,
  53. };