I'm trying to get multiple layers of conditional rendering to work in react and am running into problems.
I've simplified my usecase to the code below.
{data &&
dataIsLoading
? <h1> Loading <h1>
: !data.isError
? <Component data={data} />
: <h1> Error <h1>
}
The behavior I'd expect from the above snippet is
- Check if the data exists - if so
- Check if the data is loading - if so display 'loading', if not
- Check if the data has an error - if so display 'error', if not
- Display the data
Unfortunately when running this code I get a Null reference exception when trying to evaluate !data.isError.
That line shouldn't be executed if data is null - that's the point of the conditional rendering!
I've tried explicitly checking with data !== null &&, and I've tried replacing {data && with simply {false && and I still run into the same problem. If I'm misunderstanding how react conditional rendering works how can I safely guard against null values in this context.
undefined ? 'a' : 'b'returns me'b'- so!data.isErroris on the "false" path()around everything afterdata &&if you want that. Thedata && dataIsLoadingis only used by the first conditional. If that's false (becausedataisnull), the third operand of the conditional (starting with!data.isError) is evaluated. So:{data && (dataIsLoad ? ... : ...)}.datawould be non-nullwhendataIsLoadingis true.)