Home > Software design >  how to toggle setState value?
how to toggle setState value?

Time:03-10

this code only shows More text, there is no less button working.

how to toggle false and true for '...more' and '...less' buttons?

<Text style={styles.headerText}>Roller skating in the park</Text>
      <View style={styles.row}>
        <Text style={styles.comments}>
          {isMore
            ? 'It was an amazing time with people! Hope'
            : 'It was an amazing time with people! Hope It was an amazing time with people! Hope It was an amazing time with people! Hope It was an amazing time with people! Hope It was an amazing time with people! Hope'}
          !
        </Text>
        <View style={styles.button}>
          <Pressable
            onPress={() => {
              setisMore(false);
            }}
            disabled={!isMore}>
            <Text>{isMore ? '...more' : '...less'}</Text>
          </Pressable>
        </View>
      </View>

CodePudding user response:

You should probably set isMore to the negated value. So if isMore is false, you would want to update it to true:

<Pressable
  onPress={() => {
    setisMore(!isMore);
  }}
  disabled={!isMore}> //why do you disable the Pressable? shouldn't it be able to toggle?
  <Text>{isMore ? '...more' : '...less'}</Text>
</Pressable>

CodePudding user response:

Use the ! operator to define a toggling state.

For example, if you have:

const [isMore, setIsMore] = useState(false)

You can toggle between true and false values by triggering

setIsMore(!isMore)

What it does is it takes the value of isMore and negates it, then sets it as the default value. So if your isMore was false at first, after using

setIsMore(!isMore)

it will become true and vice versa.

Also, you should remove the disabled={!isMore} for your input.
This is because you want the '...more' button to always be clickable. You should use disabled only when you want to disable the input when a certain variable is true. So you would use it in say a form where you can only input the username if you select a 'Set Username' option.

  • Related