How do I determine the number range by pressing the button in react native?

Viewed 293

I created a structure here. When I press minus it decreases the number one by one. When I press the plus, it increases one by one. But I had a hard time doing this here. I want the numbers to be between 1 and 15. So when I press the plus button, it does not go up from 15 and when I press the minus button it does not go down from 1. How can I do it?

    import React, {useState} from 'react';
    import {View, Text, TouchableOpacity} from 'react-native';
            
    const Main = () => {
      const [counter, setCounter] = useState(1);
    
      return (
        <View>
          <TouchableOpacity onPress={() => setCounter(counter - 1)}>
            <Text>-</Text>
          </TouchableOpacity>
    
          <Text>{counter <= 1 ? 1 : counter}</Text>
    
          <TouchableOpacity onPress={() => setCounter(counter + 1)}>
            <Text>+</Text>
          </TouchableOpacity>
        </View>
      );
    };
    
    export default Main;
1 Answers

You can do the following way.

import React, {useState} from 'react';
    import {View, Text, TouchableOpacity} from 'react-native';
            
    const Main = () => {
      const [counter, setCounter] = useState(1);
      const increment =()=>{
          if(counter+1 <= 15){
             seCounter(counter+1);
           }
       }
  const decrement =()=>{
          if(counter-1 > 1){
             seCounter(counter-1);
           }
       }
      return (
        <View>
          <TouchableOpacity onPress={() => decrement()}>
            <Text>-</Text>
          </TouchableOpacity>
    
          <Text>{counter <= 1 ? 1 : counter}</Text>
    
          <TouchableOpacity onPress={() => increment()}>
            <Text>+</Text>
          </TouchableOpacity>
        </View>
      );
    };
    
    export default Main;
Related