import React from "react"
export default function App() {
const [messages, setMessages] = React.useState([])
function messCount(){
setMessages(prevMessage => prevMessage.length)
}
/**
* Challenge:
* - Only display the <h1> below if there are unread messages
*/
return (
<div>
{messages.length && <h1>You have {messages.length} unread messages!</h1>}
</div>
)
}
this is the code and the challenge commented out, i have no idea what to do please help
i tried setting up a second state with integer 0 as default, then i tried to insert with curlybrackets into the jsx markup but it didnt truly work
2
Answers
Based on comments on the question above, it sounds like the specific problem you’re asking about is:
That appears to be coming from this:
The code is successfully interpreting
messages.length
as being falsy and not outputting the<h1>
element. However, the value ofmessages.length
itself is still the result of this expression, and React is displaying that result.You can expand this into a ternary conditional operation to control the result of the expression when the value is falsy. For example:
In this case
null
will be the result of the expression whenmessages.length
is0
, and React will output nothing for it.Edit: Based on a comment below, if you must use the
&&
operator then you can do this:This relies on the actual value
false
instead of the "falsy" value0
, and the former shouldn’t output to the page.You can solve the Challenge by dynamically rendering the
<h1>
element only when there are messages.Here is the modified code:
Explanation:
<h1>
element only if there are messages(messages.length > 0
).<h1>
element in place of_
.