Araf
Araf

Reputation: 27

Using if statements in JSX

I am making a mobile app, I have a list of dictionaries like

    var userMessagesSent = [
        {sentBy: "user", content: "Hello universe"},
        {sentBy: "user", content: "Spain is big"},
        {sentBy: "araf", content: "Nobody said spain is small"},
        {sentBy: "user", content: "Yeah you are right"}    
    ];

And I also have a ScrollView, like

<ScrollView style={styles.scrollArea}>
                {
                    userMessagesSent.map((item, index) =>
                        <Text></Text>
                    )
                }
                </ScrollView>

Now isnide that mapping, I want to check if the item.sentBy is "user" or "araf". If it's "araf" then it will have a SafeAreaView with some styles, otherwise it will have another SafeAreaView with completely different styles. How can I make something like that?

Upvotes: 0

Views: 42

Answers (1)

Bad Dobby
Bad Dobby

Reputation: 871

<ScrollView style={styles.scrollArea}>
  {userMessagesSent.map((item, index) => {
    if (item.sentBy === 'araf') {
      return (
        <SafeAreaView>
          blabla
        </SafeAreaView>
      )
    }

    return (
      <Text></Text>
    )
  })}
</ScrollView>

But actually, this is not good to cooperate with other developers (including myself of long future, who has forgotten some contexts behind)

So, I recommend to make some components and get rid off conditions from jsx.

const MessageFromUser = ({ message }) => (
  <Text>
    {message.content}
  </Text>
);

const MessageFromAraf = ({ mesasge }) => (
  <SafeAreaView>
    {message.content}
  </SafeAreaView>
);

const renderMessage = (message, index) => {
  switch(message.sentBy) {
    case 'araf': return <MessageFromAraf message={message} />;
    case 'user': return <MessageFromUser message={message} />;
    default: return <Text>unexpected message.sentBy :(</Text>;
  }
}

const YourOriginalComponent = () => {
  <ScrollView style={styles.scrollArea}>
    {userMessagesSent.map(renderMessage)}
  </ScrollView>
}

Upvotes: 2

Related Questions