Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading