Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react native TouchableOpacity, different functions by first and second click

I’m creating a simple text-to-speech function for my react native app.
I have a button, when you click it for the first time, it will read the text and play the sound.
But I want to make it dynamic. For example: If you click again it should stop, if click again, should play again, etc…..
But now, it is only available for playing the sound with any click.
Where/how should I execute the stopReadText()?
I still don’t have any idea about this. Thanks a lot.

Here is the code:

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

  return (
    <View>
      <TouchableOpacity onPress=(readText)>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )

(I am using expo-speech)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it by taking on a boolean state variable:

import { useState } from 'react';

const [isPlay,setIsPlay]=useState(false)

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

const handlePlay =() =>{
  if(!setIsPlay){
      readText()
      setIsPlay(true)
  }
  else {
      stopReadText()
      setIsPlay(false)
  }

 }


  return (
    <View>
      <TouchableOpacity onPress={handlePlay}>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading