LikeButton.jsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import { createSubscribedElement } from './UnstatedUtils';
  4. import AppContainer from '../services/AppContainer';
  5. class LikeButton extends React.Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. isLiked: !!props.isLiked,
  10. };
  11. this.handleClick = this.handleClick.bind(this);
  12. }
  13. handleClick(event) {
  14. event.preventDefault();
  15. const { appContainer } = this.props;
  16. const pageId = this.props.pageId;
  17. if (!this.state.isLiked) {
  18. appContainer.apiPost('/likes.add', { page_id: pageId })
  19. .then((res) => {
  20. this.setState({ isLiked: true });
  21. });
  22. }
  23. else {
  24. appContainer.apiPost('/likes.remove', { page_id: pageId })
  25. .then((res) => {
  26. this.setState({ isLiked: false });
  27. });
  28. }
  29. }
  30. isUserLoggedIn() {
  31. return this.props.appContainer.currentUserId != null;
  32. }
  33. render() {
  34. // if guest user
  35. if (!this.isUserLoggedIn()) {
  36. return <div></div>;
  37. }
  38. const btnSizeClassName = this.props.size ? `btn-${this.props.size}` : 'btn-md';
  39. const addedClassNames = [
  40. this.state.isLiked ? 'active' : '',
  41. btnSizeClassName,
  42. ];
  43. const addedClassName = addedClassNames.join(' ');
  44. return (
  45. <button
  46. type="button"
  47. href="#"
  48. title="Like"
  49. onClick={this.handleClick}
  50. className={`btn btn-circle btn-outline-info border-0 ${addedClassName}`}
  51. >
  52. <i className="icon-like"></i>
  53. </button>
  54. );
  55. }
  56. }
  57. /**
  58. * Wrapper component for using unstated
  59. */
  60. const LikeButtonWrapper = (props) => {
  61. return createSubscribedElement(LikeButton, props, [AppContainer]);
  62. };
  63. LikeButton.propTypes = {
  64. appContainer: PropTypes.instanceOf(AppContainer).isRequired,
  65. pageId: PropTypes.string,
  66. isLiked: PropTypes.bool,
  67. size: PropTypes.string,
  68. };
  69. export default LikeButtonWrapper;