import React, { useState, useRef } from 'react';
import Speech from 'react-speech';
function MyComponent() {
const [currentPlayingId, setCurrentPlayingId] = useState(null);
const [isPlaying, setIsPlaying] = useState(false);
const speechRef = useRef();
useEffect(() => {
...
togglePlayPause(224)
...
}
}, [...]);
const togglePlayPause = (id) => {
if (currentPlayingId === id) {
// If the clicked item is currently playing, pause it
setIsPlaying(false);
} else {
// If another item (or no item) is playing, start the clicked item
setCurrentPlayingId(id);
setIsPlaying(true);
}
};
return (
<div>
{items.map((item) => (
<Speech
ref={speechRef}
key={item.id}
onClick={() => togglePlayPause(item.id)}
stop={!isPlaying || currentPlayingId !== item.id}
pause={!isPlaying || currentPlayingId !== item.id}
resume={isPlaying && currentPlayingId === item.id}
lang="en-GB"
textAsButton="Speak"
/>
))}
</div>
);
}
I want to trigger the speech item not via onClick event but via useEffect. Why is this code not working, I assume the way to go is to use ref differently. A usage of ref.current might be the solution.
Update: Turns out you can't trigger speech without the visitor clicking a button in chrome, which makes sense if I think about the yelling that awaited you when you clicked on a website back in the day.
The Speech component features four buttons:- play, stop, pause, and resume. To utilize the button functionality, simply pass a value
trueto the corresponding prop of the Speech component.You can easily change the audio states (play, stop, pause, resume) by clicking on the respective buttons, no need for useEffect or useRef hooks.
Here is the basic implementation of react-speech, following the idiomatic approach.
SpeechItem.js
TextToSpeech.js
SpeechStyles.js
If you wanna play around with the code