Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSX if-else condition

My simple component looks like this:

function Messages(props) {
  return (
    <View>
      <View
        style={styles.messageWrapper}
      >
        <View style={styles.isNotMine}>
          <View
            style={styles.message}
          >
            <Text>{props.text}</Text>
            <Text style={styles.messageTime}>{props.time}</Text>
          </View>
        </View>
     
      </View>
    </View>

  );
}

export default Messages;

I want to put some logic into JSX, but don’t know how to find out more native and convenient way. I have to replace style with style called {styles.isMine}.

...
(props.isMine)? <View style={styles.isMine}> : <View style={styles.isNotMine}>  // gained error because non-closed tag
...   

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In this particular situation, you don’t want to change the entire View component, but rather just the individual style, which you can do by putting the ternary expression within the style prop, for example:

<View style={props.isMine ? styles.isMine : styles.messageInner}> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading