0

I am a learning react native and trying to apply an if condition based on map value but getting error

enter image description here

render() {
        return (
            <View>
                <Text>My List view</Text>
                {
                    this.state.fruits.map((item) => (

                        { if(item.id % 2 == 0) {
                        console.log("Even Number")
                    }}

                <Text key={item.id}>
                    {item.id + ". " + item.name}
                </Text>
                    ))
                }

            </View>
        )
    }

3 Answers 3

1
  • You need to start your map with brackets {

  • remember to add a return statement when you want to output anything in your map loop

  • seems like there were a stray bracket }

result:

{fruits.map((item) => {
  if (item.id % 2 == 0) {
    console.log('Even Number');
  }

  return <Text key={item.id}>{item.id + '. ' + item.name}</Text>;
})}

Sign up to request clarification or add additional context in comments.

Comments

1

Not sure what you are doing here

{
     this.state.fruits.map((item) => (
     { if(item.id % 2 == 0) {
     console.log("Even Number")
}}

But this looks so wrong.

This

.map((item) => (

means you are returning something and I don't think you can have if-else directly in return statement.

I think what you meant to do is

{
     this.state.fruits.map((item) => {
     if(item.id % 2 == 0) {
     console.log("Even Number")
     } 
     return 
    // whatever you want to return 
}}

Comments

1
render() {
        return (
            <View>
                <Text>My List view</Text>
                {
                    this.state.fruits.map((item) => {

                        if(item.id % 2 == 0) {

                           console.log("Even Number")

                        }

                        return( <Text key={item.id}>{item.id + ". " + item.name </Text> )
                    
                    })
                }

            </View>
        )
    }

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.