Why if-else is not working in this react code, cause I am not getting output?

I was trying to achieve something like this in react
e.g. user enter his/her age and when click the button following logic should work

if age>18 then Eligible for Passport
else Not eligible

But I am getting no output when I enter the age and click the Enter button.

import { useState } from "react";



function App() 
{
    const[age,`your text`setAge]=useState(0)
    const handleInput= (event)=>{setAge(event.target.value)}

    const Checker = ()=>{
    if(age>18){
      return <h1>Eligible for Cnic</h1>
    }else{
      return <h1>Not-Eligible for Cnic</h1>
    }
    }
  
    return (
    <div className="App">
    <input type="text" onChange={handleInput}/>
    <button onClick={()=><Checker/>}>Check</button>
    {/* <Checker/> */}
    </div>
  );
}
``your text``
export default App;

This code is showing no output when button click is used but without button click it shows the output

>Solution :

You almost certainly want a second state variable here, and then use that as part of your normal render.

import { useState } from "react";

export default function App() 
{
    const [age, setAge] = useState(0);
    const [verified, setVerified] = useState(false);

    const handleInput = ({ target }) => setAge(target.value);
    const verifyAge = () => setVerified(age > 18);
  
    return (
      <div className="App">
        <input type="text" onChange={handleInput} placeholder="Your age"/>
        <button onClick={verifyAge}>Check</button>
        <p>{verified? `` : `Not-`}Eligible for Cnic</p>
      </div>
    );
}

Leave a Reply