mobilusoss / react-web-notification

React component with HTML5 Web Notification API
http://mobilusoss.github.io/react-web-notification
MIT License
270 stars 82 forks source link

Create a react hook based example #81

Open 2567910 opened 3 years ago

2567910 commented 3 years ago

Hi, i need a react hook based example.

If no one has done this i can create it and create a pull request with this issue.

2567910 commented 3 years ago

Here my code for a version without the sw.js stuff:


import React, { useEffect, useState } from 'react'
import Notification from 'react-web-notification';

//Component source: https://github.com/mobilusoss/react-web-notification/tree/develop/example

const OpenQuestionNotification = (props) => {

  const [ignore, setIgnore] = useState(false)
  const [title, setTitle] = useState('')
  const [trigger, setTrigger] = useState(true)
  const [options, setOptions] = useState({})

  useEffect(() => {
    if(trigger){
      handleButtonClick()
      document.getElementById('sound').muted = false
      document.getElementById('sound').play()
    }
  }, [trigger)

  const handleButtonClick = () => {
    if (ignore) {
      return;
    }
    setTitle('Test')
    setOptions({
      tag: Date.now(),
      body: 'Test 2',
      icon: 'favicon-32x32.png',
      lang: 'de',
      dir: 'ltr',
      sound: 'https://www.lukasseyfarth.com/vendor/ubi-bing.mp3'  // no browsers supported https://developer.mozilla.org/en/docs/Web/API/notification/sound#Browser_compatibility
    })
  }
    return (
      <div>
        <Notification
          ignore={ignore}
          timeout={5000}
          title={title}
          options={options}
        />
        <audio id='sound' preload='auto' muted>
          <source src='https://www.lukasseyfarth.com/vendor/ubi-bing.mp3' type='audio/mpeg' />
          <source src='https://www.lukasseyfarth.com/vendor/sound.ogg' type='audio/ogg' />
          <embed hidden={true} autostart='false' loop={false} src='https://www.lukasseyfarth.com/vendor/ubi-bing.mp3' />
        </audio>
      </div>
    )
}
export default OpenQuestionNotification`
eliaoucohen72 commented 3 years ago

In my home component

const [windowsNotificationOptions, setWindowsNotificationOptions] = useState({ icon:myIcon, lang: props.language, dir: 'ltr', silent: false, ignore: true });

When I want to launch a notification setWindowsNotificationOptions({ ...windowsNotificationOptions, body: message, tag: Date.now(), ignore: false });

<WindowsNotification options={windowsNotificationOptions} />

Windows Notification component

import React, { memo } from 'react';
import PropTypes from 'prop-types';
import Notification from 'react-web-notification';

function WindowsNotification(props) {
  return <Notification timeout={5000} title="Widebridge" options={props.options} ignore={props.options.ignore} />;
}

WindowsNotification.propTypes = {
  options: PropTypes.object
};

export default memo(WindowsNotification);