Skip to content

Instantly share code, notes, and snippets.

@wasabigeek
Last active January 3, 2021 09:50
Show Gist options
  • Save wasabigeek/0827435d4c38c5de7d8d96f971db4bb1 to your computer and use it in GitHub Desktop.
Save wasabigeek/0827435d4c38c5de7d8d96f971db4bb1 to your computer and use it in GitHub Desktop.
Stimulus VS React
import React, { useState } from "react";
const SubscribeButton = ({ initialSubscribed = false }) => {
const [isSubscribed, setIsSubscribed] = useState(initialSubscribed);
const [isHovered, setIsHovered] = useState(false);
const handleClick = () => {
if (isSubscribed) {
// DELETE destroy
// imagine this is in .then()
setIsSubscribed(false);
} else {
// POST create
// imagine this is in .then()
setIsSubscribed(true);
}
}
let buttonText, buttonCss;
if (isSubscribed && isHovered) {
buttonText = "Unsubscribe?";
buttonCss = "text-red-400";
} else if (isSubscribed) {
buttonText = "Subscribed";
buttonCss = "text-gray-400";
} else {
buttonText = "Subscribe";
buttonCss = "text-green-400 hover:text-green-500";
}
return (
<button
className={buttonCss}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onClick={handleClick}
>
{buttonText}
</button>
)
}
// in view
{/*
<button
data-controller="subscribe-button"
data-action="click->subscribe-button#toggle mouseover->subscribe-button#mouseover mouseout->subscribe-button#mouseout"
>
Subscribe
</button>
*/}
import { Controller } from "stimulus"
const subscribedCss = ['text-gray-400 hover:text-red-400']
const unsubscribedCss = ['text-green-400 hover:text-green-500']
export default class extends Controller {
connect() {
this.styleButton()
}
mouseover() {
if (this.isSubscribed()) {
this.element.innerHTML = 'Unsubscribe?'
}
}
mouseout() {
if (this.isSubscribed()) {
this.element.innerHTML = 'Subscribed'
}
}
toggle() {
const initialSubscription = this.isSubscribed()
if (initialSubscription) {
// DELETE destroy
}
else {
// POST create
}
// imagine this is in .then()
this.data.set('subscribed', !initialSubscription)
this.styleButton()
}
isSubscribed() {
return JSON.parse(this.data.get('subscribed'))
}
styleButton() {
if (this.isSubscribed()) {
this.element.classList.add(...subscribedCss)
this.element.classList.remove(...unsubscribedCss)
this.element.innerHTML = 'Subscribed'
}
else {
this.element.classList.remove(...subscribedCss)
this.element.classList.add(...unsubscribedCss)
this.element.innerHTML = 'Subscribe'
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment