Would require your assistance in order to show a p tag only if value is given in the API. I receive my data from API, and sometimes the field has values and sometimes not, therefore if the item has no feed, there is an error raised Cannot read properties of null (reading 'substring')
I don't know how to check if there is no data into this field {threat.attributes.timestamp.substring(0, 10)}, because if is blank, I want to hide the entire p tag, as the field became redundant will null value.
Thank you in advance!
<div>
<p className="post__author--role">
<small>Timestamp: {threat.attributes.timestamp.substring(0, 10)}
</small>
</p>
</div>
CodePudding user response:
You can accomplish conditional rendering in React using a couple of ways
- Inline If with Logical && Operator (Since your variable is kinda long, I refactored them to a separate variable)
const data = threat.attributes.timestamp;
<div>
<p className="post__author--role">
{data && <small>Timestamp: {data.substring(0, 10)} </small>}
</p>
</div>
Thanks to short circuiting, this will only render your <small> element if threat.attributes.timestamp exists
- Ternary operators
Ternary operator is kind of another way to do inline If
const data = threat.attributes.timestamp;
<div>
<p className="post__author--role">
<small>Timestamp: {data ? data.substring(0, 10) : null}
</small>
</p>
</div>
You can replace the null with something you want to display in case of no data, for example: <span>No timestamp</span>
- Optional chaining
<div>
<p className="post__author--role">
<small>Timestamp: {threat.attributes.timestamp?.substring(0, 10)}
</small>
</p>
</div>
With optional chaining, the whole expression will return undefined if .timestamp fails to exist
