0
import React from 'react';
import { View, Text } from 'react-native';

let globalIsTotal =false;
const component = ({ isTotal }) => {
  const { mainLabelStyle } = styles;

  globalIsTotal = isTotal;
  return (
    <View>
      <Text style={mainLabelStyle}>Hello World</Text>
    </View>
  );
};

const styles = {
  mainLabelStyle: {
    fontSize:28,
    flex: 1,
    fontWeight: () => {
      if(globalIsTotal===true){
        return 'bold';
      }
      return 'normal';
    }
  }
}

I'm trying to set the fontWeight of style depending on globalIsTotal value, but seems like the function is not being trigger. Wondering if this is the right way to handle such styling logic? This is a functional component which is reusable and props isTotal pass from caller

3 Answers 3

1

I would achieve this like so:

Remove fontWeight from the style object

const styles = {
  mainLabelStyle: {
    fontSize:28,
    flex: 1
  }
}

And add it like so:

<Text style={[mainLabelStyle, { fontWeight: globalIsTotal ? 'bold' : 'normal'}]}>Hello World</Text>
Sign up to request clarification or add additional context in comments.

Comments

1

You should use ternary expressions to trigger conditionals in objects, like:

mainLabelStyle: {
  fontSize:28,
  flex: 1,
  fontWeight: globalIsTotal ? 'bold' : 'normal'
}

Comments

0

Here's my option about your issue :

let globalIsTotal =false;
const component = ({ isTotal }) => {
  const { mainLabelStyle } = styles;

  globalIsTotal = isTotal;
  return (
    <View>
      <Text style={globalIsTotal==true ? [styles.mainLabelStyleBold] : [styles.mainLabelStyleNormal]}>Hello World</Text>
    </View>
  );
};

const styles = {
  mainLabelStyleNormal: {
    fontSize:28,
    flex: 1,
    fontWeight: 'normal'
  }
  mainLabelStyleBold: {
    fontSize:28,
    flex: 1,
    fontWeight: 'bold'
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.