JamesBrill / react-speech-recognition

💬Speech recognition for your React app
https://webspeechrecognition.com/
MIT License
657 stars 119 forks source link

Using onTranscriptionChanged(text) {} on react class component #45

Closed LordHaywood closed 4 years ago

LordHaywood commented 4 years ago

How do you mount SpeechRecognition onto a react class component. Ideally I would like a method for onTranscriptionChanged: (text: string) => void in my component

JamesBrill commented 4 years ago

Hi Thomas! Firstly, I would say that if you are using React 16.8 or above and can refactor your class component into a functional component, that would be the best solution and would make your React app cleaner overall. If you did that, you could use react-speech-recognition version 3 and utilise the useSpeechRecognition hook and useEffect to detect transcription changes.

If that's not an option, you will need to use version 2 (the latest version 2 was 2.1.4 and is documented here). This offers a higher-order component that injects the transcript into your component. To pick up transcript changes in your class component with this older version, you can add a lifecycle hook to your component like this:

componentWillReceiveProps(nextProps) {
  if (this.props.transcript !== nextProps.transcript) {
    onTranscriptionChanged(nextProps.transcript)
  }
}

If you want the features available in version 3 (e.g. commands) but still need to use a class component, I believe there are hacky ways to get React hooks to work with class components (e.g. this article), but I wouldn't recommend it as they are two different paradigms for writing React components.

LordHaywood commented 4 years ago

Perfect thanks, got it sorted!