react-web-notification icon indicating copy to clipboard operation
react-web-notification copied to clipboard

Create a react hook based example

Open 2567910 opened this issue 4 years ago • 2 comments

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 avatar Apr 30 '21 17:04 2567910

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`

2567910 avatar Apr 30 '21 18:04 2567910

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);

eliaoucohen72 avatar Aug 19 '21 14:08 eliaoucohen72