If condition inside of map() React

Reactjs

Reactjs Problem Overview


I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

render() {
  return (
    <div>
      <div className="box">
        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (
              <h1>hejsan</h1>
            )}
          )}
      </div>
    </div>
  )
}

But it doesn't work..! Here's the error:

Screenshot

I appreciate all the help I can get!

Reactjs Solutions


Solution 1 - Reactjs

You are using both ternary operator and if condition, use any one.

By ternary operator:

.map(id => {
    return this.props.schema.collectionName.length < 0 ?
        <Expandable>
            <ObjectDisplay
                key={id}
                parentDocumentId={id}
                schema={schema[this.props.schema.collectionName]}
                value={this.props.collection.documents[id]}
            />
        </Expandable>
    :
        <h1>hejsan</h1>
}

By if condition:

.map(id => {
    if(this.props.schema.collectionName.length < 0)
        return <Expandable>
                  <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                  />
              </Expandable>
    return <h1>hejsan</h1>
}

Solution 2 - Reactjs

If you're a minimalist like me. Say you only want to render a record with a list containing entries.

<div>
  {data.map((record) => (
    record.list.length > 0
      ? (<YourRenderComponent record={record} key={record.id} />)
      : null
  ))}
</div>

Solution 3 - Reactjs

There are two syntax errors in your ternary conditional:

  1. remove the keyword if. Check the correct syntax [here][1].

  2. You are missing a parenthesis in your code. If you format it like this:

     {(this.props.schema.collectionName.length < 0 ? 
        (<Expandable></Expandable>) 
        : (<h1>hejsan</h1>) 
     )}
    

Hope this works! [1]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Solution 4 - Reactjs

This one I found simple solutions:

row = myArray.map((cell, i) => {

    if (i == myArray.length - 1) {
      return <div> Test Data 1</div>;
    }
    return <div> Test Data 2</div>;
  });

Solution 5 - Reactjs

Remove the if keyword. It should just be predicate ? true_result : false_result.

Also ? : is called ternary operator.

Solution 6 - Reactjs

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin Nordstr&#246;mView Question on Stackoverflow
Solution 1 - ReactjsMayank ShuklaView Answer on Stackoverflow
Solution 2 - ReactjsRaymond WachagaView Answer on Stackoverflow
Solution 3 - ReactjsdhalimanView Answer on Stackoverflow
Solution 4 - ReactjsHarshal WaniView Answer on Stackoverflow
Solution 5 - ReactjsHuy LeView Answer on Stackoverflow
Solution 6 - ReactjsNesha ZoricView Answer on Stackoverflow