LikeButton.jsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. export default class LikeButton extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. isLiked: !!props.isLiked,
  8. };
  9. this.handleClick = this.handleClick.bind(this);
  10. }
  11. handleClick(event) {
  12. event.preventDefault();
  13. const pageId = this.props.pageId;
  14. if (!this.state.isLiked) {
  15. this.props.crowi.apiPost('/likes.add', {page_id: pageId})
  16. .then(res => {
  17. this.setState({isLiked: true});
  18. });
  19. }
  20. else {
  21. this.props.crowi.apiPost('/likes.remove', {page_id: pageId})
  22. .then(res => {
  23. this.setState({isLiked: false});
  24. });
  25. }
  26. }
  27. isUserLoggedIn() {
  28. return this.props.crowi.me !== '';
  29. }
  30. render() {
  31. // if guest user
  32. if (!this.isUserLoggedIn()) {
  33. return <div></div>;
  34. }
  35. const btnSizeClassName = this.props.size ? `btn-${this.props.size}` : 'btn-md';
  36. const addedClassNames = [
  37. this.state.isLiked ? 'active' : '',
  38. btnSizeClassName,
  39. ];
  40. const addedClassName = addedClassNames.join(' ');
  41. return (
  42. <button href="#" title="Like" onClick={this.handleClick}
  43. className={`btn-like btn btn-default btn-circle btn-outline ${addedClassName}`}>
  44. <i className="icon-like"></i>
  45. </button>
  46. );
  47. }
  48. }
  49. LikeButton.propTypes = {
  50. crowi: PropTypes.object.isRequired,
  51. pageId: PropTypes.string,
  52. isLiked: PropTypes.bool,
  53. size: PropTypes.string,
  54. };