Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created November 11, 2021 21:11
Show Gist options
  • Save lejonmanen/5d0634cdef5ac62682fb7d16b30dce3d to your computer and use it in GitHub Desktop.
Save lejonmanen/5d0634cdef5ac62682fb7d16b30dce3d to your computer and use it in GitHub Desktop.
Use Notification API to display notifications from a React component.
import { useState, useEffect } from 'react'
// Be aware that notifications are fickle creatures. You may have to jump through some hoops to get them working on your desired browsers and platforms. The following code is tested on Firefox for Windows. But you should be able to modify it to work in other environments.
const Notis = () => {
const [canUse, setCanUse] = useState(false)
const [clicks, setClicks] = useState(0)
const [fromNotification, setFromNotification] = useState(null)
useEffect(() => {
// Find out whether we can use notifications at all
Notification.requestPermission().then(result => {
if( result === 'granted' )
setCanUse(true)
})
}, [])
// Functions that show notifications that can update state variables when clicked
function showNotificationWithData(title, data) {
let n = new Notification(title)
n.addEventListener('click', () => {
setFromNotification(data)
})
}
const showN = () => {
let n = new Notification('Notification!', {body: 'This is an example. How many times can you click me and my friends?'})
n.addEventListener('click', () => {
// Must use the callback form of the set function because this function is a closure. It would remember the old values, and state would be set to specific numbers rather than being increased by one.
setClicks(state => state + 1)
})
}
return (
<div>
<h3> Notification API - {canUse ? 'enabled' : 'cannot use'}. </h3>
<p>
<button disabled={!canUse} onClick={showN}> Show counting notification </button>
You've clicked {clicks} time(s) on the notifications.
</p>
<p>
Show notification: <br/>
<button onClick={() => showNotificationWithData('Red', 'red data')}> Red </button>
<button onClick={() => showNotificationWithData('Yellow', 'yellow data')}> Yellow </button>
<button onClick={() => showNotificationWithData('Green', 'green data')}> Green </button>
</p>
{fromNotification
? <p> You clicked a notification with the data: "{fromNotification}". </p>
: null
}
</div>
)
}
export default Notis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment