Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

audio in react

import React, { useState, useEffect } from "react";

const useAudio = url => {
  const [audio] = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

  const toggle = () => setPlaying(!playing);

  useEffect(() => {
      playing ? audio.play() : audio.pause();
    },
    [playing]
  );

  useEffect(() => {
    audio.addEventListener('ended', () => setPlaying(false));
    return () => {
      audio.removeEventListener('ended', () => setPlaying(false));
    };
  }, []);

  return [playing, toggle];
};

const Player = ({ url }) => {
  const [playing, toggle] = useAudio(url);

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
};

export default Player;
Comment

PREVIOUS NEXT
Code Example
Javascript :: link script react17 
Javascript :: bodyparser purpose 
Javascript :: roblox headshot image 
Javascript :: laravel query json 
Javascript :: how to numeric value is after point 2 values in javascript 
Javascript :: javascript get a random array from 1 to n 
Javascript :: xhr 
Javascript :: javascript access php variable 
Javascript :: nested shorthand if javascript 
Javascript :: redux devtools extension npm 
Javascript :: how to push array in redux 
Javascript :: store data in array jquery 
Javascript :: formdata append react js 
Javascript :: how to create list of years js 
Javascript :: assign an element value as key in array of objects 
Javascript :: javascript get element by custom attribute 
Javascript :: js location 
Javascript :: react how to create range 
Javascript :: how to check if a folder exist if not then create nodejs 
Javascript :: javascript newline in alert 
Javascript :: remove empty element from array js 
Javascript :: remove one array from another javascript 
Javascript :: add month date now javascript 
Javascript :: jquery read query string 
Javascript :: string split javascript 
Javascript :: react-select default menu open 
Javascript :: jquery on hover dynamic elements 
Javascript :: javascript range of integers with spread 
Javascript :: how to check consecutive characters in javascript 
Javascript :: how to validate a string using regular expression in javascript 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =