use ternary operator with useState in React Native

640 Views Asked by At

I have a problem with ternary operator in my code

  1. I 2 states that holds true/false regarding whenever a button is pressed:

Here(sorry i have a problem formatting it in block code)

const [lineChecked, setLineChecked] = useState(false);
const [pieChecked, setPieChecked] = useState(false);

Here is the Touchable Opacity with onPress that i designated to turn 1 state to true, and other to false(i have 2 of this - the other one is the opposite):

<TouchableOpacity
      onPress={() => {
        setPieChecked(true);
        setLineChecked(false);
      }}
    >

What i want to accomplish is that when i press 1 touchable opacity graph X will be presented and when i press the other touchable opacity the other graph will be presented, initial state is that none of the graphs is presented.

here is what i tried:

 <View style={styles.graphsPart}>
    {lineChecked == "true" ? (
      <LineChart
        data={data}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
    {pieChecked == "true" ? (
      <LineChart
        data={dataTwo}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
  </View>

Suggestions??

2

There are 2 best solutions below

3
On BEST ANSWER
 <View style={styles.graphsPart}>
    {lineChecked ? (
      <LineChart
        data={data}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
    {pieChecked ? (
      <LineChart
        data={dataTwo}
        width={screenWidth - 10}
        height={220}
        chartConfig={chartConfig}
        yAxisLabel="₪"
      />
    ) : null}
  </View>

you need to check the value of that no need for == 'true'

0
On
(true == 'true') === false

You need to compare against booleans (true), not strings ('true').

Better still, you can just check for general truthiness:

const val = true

const result = val ? 'yes' : 'no'
// if val is a boolean, this will work the same as
// `val === true ? 'yes' : 'no'`