skip to Main Content

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
...   

3

Answers


  1. 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}> 
    
    Login or Signup to reply.
  2. You can add if-else conditions to the prop, rather than the component:

    <View styles={props.isMine ? styles.isMine : styles.isNotMine}>
    
    Login or Signup to reply.
  3. You mentioned ‘gained error because non-closed tag’. This is happening because you can’t use the ternary operator only for the opening tag. You need to use it for both together, or use a self closing tag.

    Fixed v1 – Not useful because you probably want to pass child props inside the View component.

    (props.isMine) ? <View style={styles.isMine}/> : <View style={styles.isNotMine}/> 
    

    Fixed v2 – more useful

    (props.isMine) ? <View style={styles.isMine}> My Stuff </View> : <View style={styles.isNotMine}> Not My Stuff </View> 
    

    I thought I would mention this because that the root cause of your error. You seem to have already solved the problem though.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search