If condition inside of map() React

Viewed 233369

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!

8 Answers

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>

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>;
  });

That the ternary operator works but not if-else statements is rather ridiculous and makes complex logic a pain. The former seems to be the only solution though.

Just in case:

If only: (Use && without ? : or else)

When you don't have to return anything when else

Examples: (Array or Object)

// const someArray = ['a', 'b', 'c']
{someArray.map(
  (v) =>
    someCondition && (
      <></> // {v}
    )
)}

// const someObject = {a: '1', b: '2', c: '3'}
{Object.keys(someObject).map(
  (k) =>
    someCondition && (
      <></> // {someObject[k]} (Remember: add key={k} in wrapper)
    )
)}
Related