Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created December 27, 2021 15:35
Show Gist options
  • Save cameronp98/0d48e0020b4e13208bef3c1a7f24d773 to your computer and use it in GitHub Desktop.
Save cameronp98/0d48e0020b4e13208bef3c1a7f24d773 to your computer and use it in GitHub Desktop.
Action button (for use with e.g tailwindcss)
import React, { useState } from 'react'
const ActionButton = ({ action }) => {
const [btnState, setBtnState] = useState('idle')
const doLoad = () => {
if (btnState === 'idle') {
setBtnState('loading')
action().then(() => {
setBtnState('done')
})
}
}
return (
<>
{btnState === 'idle' ? (
<IdleButton doLoad={doLoad} />
) : btnState === 'loading' ? (
<LoadingButton />
) : (
<DoneButton />
)}
</>
)
}
const IdleButton = ({ doLoad }) => {
return (
<button className="cursor-pointer" onClick={doLoad}>
Load
</button>
)
}
const LoadingButton = () => {
return <button className="cursor-progress">Loading...</button>
}
const DoneButton = () => {
return (
<button className="cursor-not-allowed" disabled>
Done.
</button>
)
}
export default ActionButton
import React, { useState } from 'react'
import ActionButton from './components/ActionButton'
function App() {
const btnAction = () => {
console.log('Started action.')
return new Promise((resolve) => {
setTimeout(() => {
console.log('Done!')
resolve()
}, 2000)
})
}
return (
<>
<ActionButton action={btnAction} />
</>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment