Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Yes, using a ternary operator in JSX to conditionally render components/values looks a bit ugly, but nothing is stopping you from making a wrapper component like:

Couldn't you put that in a function that returns the correct JSX element or am I misunderstanding the problem? Something like:

  renderThing(number) {
    if(number > 0) return <div>...</div>
    return <div>...</div>
  }


  const Page = () => {
    return <div>{renderThing(someNumber)}</div>
  }

Simple ternaries are fine IMO but thats what I do when the logic gets complicated. I never used a nested ternary in that situation, for example.


You have to be careful with code like the above in React. Using a lower-cased function that returns JSX but is not rendered with react.createElement (either directly or via the JSX syntax) can lead to confusing violations of the rules of hooks as it relates to exact ordering of calls.

This is because it doesn't get registered as it's own component, so conditionally called children with hooks may cause errors.


The render function is a pure function returning jsx based on the input, not invoking any stateful operation like "functional hook".

So this style of code is fine in react


Does simply uppercasing it avoid these concerns?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: