skip to Main Content
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


  1. Based on comments on the question above, it sounds like the specific problem you’re asking about is:

    there’s a zero (on the screen)if i delete all the items in the array

    That appears to be coming from this:

    {messages.length && <h1>You have {messages.length} unread messages!</h1>}
    

    The code is successfully interpreting messages.length as being falsy and not outputting the <h1> element. However, the value of messages.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:

    {messages.length ? <h1>You have {messages.length} unread messages!</h1> : null}
    

    In this case null will be the result of the expression when messages.length is 0, and React will output nothing for it.


    Edit: Based on a comment below, if you must use the && operator then you can do this:

    {messages.length > 0 && <h1>You have {messages.length} unread messages!</h1>}
    

    This relies on the actual value false instead of the "falsy" value 0, and the former shouldn’t output to the page.

    Login or Signup to reply.
  2. You can solve the Challenge by dynamically rendering the <h1> element only when there are messages.

    Here is the modified code:

    import React from "react";
    
    export default function App() {
    
        const [messages, setMessages] = React.useState(["a", "b"]);
    
        /**
         * Challenge:
         * - Only display the <h1> below if there are unread messages
         */
    
        return (
            <div>
                {/* Conditionally render the <h1> element */}
    
                {messages.length > 0 && (
                    <h1>You have {messages.length} unread messages!</h1>
                )}
            </div>
        );
    }
    

    Explanation:

    1. We use a conditional rendering to render the <h1> element only if there are messages(messages.length > 0).
    2. If there are unread messages, we display the count of message inside the <h1> element in place of _.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search