Home > Back-end >  Disable TouchableOpacity after 5 clicks - React Native
Disable TouchableOpacity after 5 clicks - React Native

Time:11-19

I am pulling memes from an API and only want to show 5 memes therefore I tried to disable the touchableOpacity after certian number of clicks. Any ideas on how I can do that?


const link = 'https://meme-api.herokuapp.com/gimme'

class Meme extends React.Component {
  constructor() {
    super()
    this.state = {
      loading: false,
      data: {
        postLink: "sample data",
        subreddit: "sample data",
        title: "sample data",
        url: 'https://poster.keepcalmandposters.com/8170567.jpg'
      }
    }
  }

  load = () => {
    this.setState({ loading: true })
    axios.get(link).then(res => {
      this.setState({
        data: res.data,
        loading: false,
      })
      console.log(Object.keys(res.data))
    })
  }

This is where the "button" is


render() {
    return (  
      <View>
        <View style={styles.container}>
    
          <View style={styles.imageView}>
            <ProgressiveImage source={{ uri: this.state.data.url }} />
          </View>

          <TouchableOpacity style={styles.button} 
          onPress={() => {this.load()}} >
          
            <Text style={styles.btnText}>Click to open a meme!</Text>
          </TouchableOpacity>

        </View>
        <AnimatedLoader
          visible={this.state.loading}
          overlayColor="rgba(255,255,255,0.75)"
          source={require("../loader.json")}
          animationStyle={styles.lottie}
          speed={1} />
      </View>
      
      
    );
  }
};

I tried using state/setState for disabiling the button but nothing seems to work. I am okay with just disabiling the button but I tried it with two different pressHandlers, one for this.load() and another for disabling after a click but both of them does not work at the same time.

CodePudding user response:

You need to create a counter state for the button and set the disable properties as well. Here's a simple example for it.


class Meme extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0
    };
  }

  load = () => {
    this.setState({ count   })
    // and others logic
  }

  render() {
    return (
      <TouchableOpacity onPress={() => {this.load()}} disabled = {this.state.count == 5 ? true : false}>
        <Text>Click to open a meme!</Text>
      </TouchableOpacity>
    );
  }
}

CodePudding user response:

functional component example for this. 

const Meme = () => {
 const [count, setCount] = useState(0)

  const loadForAPI = () => {
   setCount(count => count   1)
  }

  render() {
    return (
      <TouchableOpacity onPress={() => {loadForAPI()}} disabled = {count == 5 ? true : false}>
        <Text>Click to open a meme!</Text>
      </TouchableOpacity>
    );
  }
}

export default Meme;
  • Related