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
3
Answers
You can’t return a DOM element from an
onChange
event, nothing will be done with the returned value.There are much better ways of doing this.
As requested by OP in the comment, I’ve
Added a
result
useState
where we save the string you want to showOn button click, call
onButtonClick
that will use thesetResult
hook to save theresult
with youif
statement, that I’ve changed to an inline variantIf
result
is a true value, showresult
wrapped inh1
Updated snippet:
You almost certainly want a second state variable here, and then use that as part of your normal render.