| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import React from 'react';
- import PropTypes from 'prop-types';
- import { createSubscribedElement } from './UnstatedUtils';
- import AppContainer from '../services/AppContainer';
- class LikeButton extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- isLiked: !!props.isLiked,
- };
- this.handleClick = this.handleClick.bind(this);
- }
- handleClick(event) {
- event.preventDefault();
- const { appContainer } = this.props;
- const pageId = this.props.pageId;
- if (!this.state.isLiked) {
- appContainer.apiPost('/likes.add', { page_id: pageId })
- .then((res) => {
- this.setState({ isLiked: true });
- });
- }
- else {
- appContainer.apiPost('/likes.remove', { page_id: pageId })
- .then((res) => {
- this.setState({ isLiked: false });
- });
- }
- }
- isUserLoggedIn() {
- return this.props.appContainer.currentUserId != null;
- }
- render() {
- // if guest user
- if (!this.isUserLoggedIn()) {
- return <div></div>;
- }
- const btnSizeClassName = this.props.size ? `btn-${this.props.size}` : 'btn-md';
- const addedClassNames = [
- this.state.isLiked ? 'active' : '',
- btnSizeClassName,
- ];
- const addedClassName = addedClassNames.join(' ');
- return (
- <button
- type="button"
- href="#"
- title="Like"
- onClick={this.handleClick}
- className={`btn btn-circle btn-outline-info border-0 ${addedClassName}`}
- >
- <i className="icon-like"></i>
- </button>
- );
- }
- }
- /**
- * Wrapper component for using unstated
- */
- const LikeButtonWrapper = (props) => {
- return createSubscribedElement(LikeButton, props, [AppContainer]);
- };
- LikeButton.propTypes = {
- appContainer: PropTypes.instanceOf(AppContainer).isRequired,
- pageId: PropTypes.string,
- isLiked: PropTypes.bool,
- size: PropTypes.string,
- };
- export default LikeButtonWrapper;
|