Oyyou
Oyyou

Reputation: 618

Ternary Operator in JSX - Alternative?

I've found myself doing a lot of if-else conditions in React recently, but not actually needed anything on the else:

{node.tags ?
  <div className="tags"> {
    node.tags.map(e =>
      <p key={e}>{e}</p>
    )}
  </div> :
  <></>
}

Is there a cleaner way of doing this, or is it the standard?

I was thinking about doing it in a function - but I'm not sure what alternatives there are:

const getTags = (node) => {

  if (!node.tags) {
    return;
  }

  return (
    <div className="tags"> {
      node.tags.map(e =>
        <p key={e}>{e}</p>
      )}
    </div>
  )
}

Upvotes: 0

Views: 1327

Answers (3)

Aakash
Aakash

Reputation: 23805

I usually create a ShowHide component for all conditionals and a map-function for Arrays:

const ShowHide = ({show, children}) => show && children

const Tag = ({tag}) => <p>{tag}</p>

const mapTagsToJSX = tags => tags && tags.map(tag => (<Tag key={tag} tag={tag} />))

const Tags = ({tags}) => (
    <div>
      <ShowHide show={tags}>
          {mapTagsToJSX(tags)}
      </ShowHide>
      <ShowHide show={!tags}>
        loading tags...
      </ShowHide>
    </div>
  )
  
const useTags = () => {
  const [tags, setTags] = React.useState(null)
  React.useEffect(() => {
    setTimeout(() => {
      setTags([1,2,3])
    }, 1000)
  }, [])
  return tags;
}

const App = () => {
 const tags = useTags()
 return (<Tags tags={tags}/>)
}

const root = document.getElementById('root');

ReactDOM.render(<App />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Good Luck...

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

I like to use && for this purpose as the following:

{
  node.tags &&
  <div className="tags">
     {
         node.tags.map(e => <p key={e}>{e}</p>)
     }
  </div>  
}

You can read more about && at Conditional Rendering documentation. Especially the Inline If with Logical && Operator section which states:

You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element.

Upvotes: 2

helloitsjoe
helloitsjoe

Reputation: 6529

In most cases, you can simplify this to:

{node.tags &&
  <div className="tags"> {
    node.tags.map(e =>
      <p key={e}>{e}</p>
    )}
  </div>
}

Upvotes: 2

Related Questions