Search code examples
reactjsconditional-statements

React can not use conditionally rendering on a component due to variables being nested inside of my form


I want to conditionally render a component in this case if the user submits a wrong answer, the input is stored as a javascript object called data and gets converted to a string called userInput.

After looking around, I got recommended to create a conditional rendering with a state outside of the form, but the problem I ran across is that since the variables are initialized inside of my form, i can't use ternaries to conditionally render my component in so I'm a bit stuck in what to do.

 <main class="gameSection">
        
        <h1>Welcome to League of Wordle!</h1>
        <form
          onSubmit={handleSubmit((data) => {

            let userInput = data.guess;
            console.log(userInput);
            const championList = Object.keys(champions);


            if (userInput.valueOf().toUpperCase() !== correctChampion.valueOf().toUpperCase()) {
              <Wrong text="Class" alt="wrong img" img={wrong} />
            }
          })

          }
        >
          <input 
          {...register("guess")} class="guess_input" placeholder="Enter Champion Name Here" type="text" />
          <input class="guess_input" type="submit" />
        </form>
      </main>

Solution

  • I suggest you create a state to track if any answers submitted is wrong.

    const [isWrong, setIsWrong] = useState(false)
    

    Now, after each submit, update isWrong's value based on input.

          onSubmit={handleSubmit((data) => {
    
            let userInput = data.guess;
            console.log(userInput);
            const championList = Object.keys(champions);
    
    
            if (userInput.valueOf().toUpperCase() !== correctChampion.valueOf().toUpperCase()) {
              setIsWrong(true)
            }
            else {setIsWrong(false) } // logic in case of correct answer
          })
    
          }
        
    

    Finally, you can implement conditional rendering:

     <main class="gameSection">
        
        <h1>Welcome to League of Wordle!</h1>
        <form
          ...
        >
          <input 
          {...register("guess")} class="guess_input" placeholder="Enter Champion Name Here" type="text" />
          <input class="guess_input" type="submit" />
          {isWrong && <Wrong text="Class" alt="wrong img" img={wrong} /> }
        </form>
      </main>