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
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 thestyle
prop, for example:You can add
if-else
conditions to the prop, rather than the component: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.Fixed v2 – more useful
I thought I would mention this because that the root cause of your error. You seem to have already solved the problem though.