Re:Advice on JSX Conditionals
by 9wzYQbTYsAIc on Wednesday March 09, 2022 @03:08PM
(#30619355)
I get what you are saying. In my experience, it ends up being moot when you are explicitly trying to avoid runtime errors, because you’ll need something along the lines of “guard() && <Component />” or you could simply have “<Component />” and then within Component render have “if (!guarded) return <Fragment />”, etc.
At that point, you’ll probably need to worry about component collections containing empty elements, though. That pulls you back into the parent scope, anyways.
There’s probably a nicer way to handle it with custom hooks, though.
> I don't know whether that principle is generally true or ought to be generally true
They sure do go out of their way to make misuse of hooks a compile-time error. I think that those useful error messages go a long way to rectifying the archaic semicolon error messages of the C days.
I don't know whether that principle is generally true or ought to be generally true, but React does throw a runtime error if you render a plain JS object as a React child. This can probably also be prevented at compile time with linters or TypeScript, but given that React has to do something at runtime if it encounters an invalid child, I think throwing an error is preferable to just rendering nothing or having some undefined behavior.
In my opinion, rendering `null` is a pretty clear and explicit way to indicate you don't want to render anything. But rendering `false` (or `true`, for that matter) is not at all so clear to me. I think throwing a runtime error would be better, and would largely make the `thing && <Component />` idiom go away.