I would like to log or display in a paragraph tag the results of a function after an input. This is what I have tried:
import React, { useState } from "react";
const Measurement = () => {
const [brightness, setBrightness] = useState(0);
const [darkness, setDarkness] = useState(0);
const checkLumens = () => {
if (brightness > 120) {
return "High";
}
if (darkness < 80) {
return "Low";
}
else {
return "Not Set";
}
};
return (
<div>
<input
type="number"
onChange={(event) => setBrightness(event.target.value)}
/>
<button>Show</button>
<p>{checkLumens()}</p> //Hide by default and show {checkLumens()} after button click
</div>
);
};
export default Measurement;
Thanks for the help!
CodePudding user response:
Just add a new state variable:
import React, { useState } from "react";
const Measurement = () => {
const [brightness, setBrightness] = useState(0);
const [darkness, setDarkness] = useState(0);
const [showLumens, setShowLumens] = useState(false);
const checkLumens = () => {
if (brightness > 120) {
return "High";
}
if (darkness < 80) {
return "Low";
}
else {
return "Not Set";
}
};
return (
<div>
<input
type="number"
onChange={(event) => setBrightness(event.target.value)}
/>
<button onClick={() => setShowLumens(true)}>Show</button>
<p>{showLumens ? checkLumens() : null}</p> //Hide by default and show {checkLumens()} after button click
</div>
);
};
export default Measurement;
CodePudding user response:
import React, { useState, useEffect } from "react";
const Measurement = () => {
const [brightness, setBrightness] = useState(0);
const [darkness, setDarkness] = useState(0);
const [lumens, setLumens] = useState('Not Set')
const [show, setShow] = useState(false)
useEffect(() => {
if (brightness > 120) {
setLumens("High");
}
if (darkness < 80) {
setLumens("Low");
}
else {
setLumens("Not Set");
}
}, [darkness, brightness])
return (
<div>
<input
type="number"
onChange={(event) => setBrightness(event.target.value)}
/>
<button onClick={() => setShow(true)}>Show</button>
<p>{show && lumens}</p> //Hide by default and show {checkLumens()} after button click
</div>
);
};
export default Measurement;
CodePudding user response:
Create a state to show and hide the lumens value using useState, and change the value on button click
const Measurement = () => {
const [brightness, setBrightness] = useState(0);
const [darkness, setDarkness] = useState(0);
const [showLumens, setShowLumnes] = useState(false);
const checkLumens = () => {
if (brightness > 120) {
return "High";
}
if (darkness < 80) {
return "Low";
}
else {
return "Not Set";
}
};
return (
<div>
<input
type="number"
onChange={(event) => setBrightness(event.target.value)}
/>
<button onClick={()=>setShowLumnes(true)}>Show</button>
{showLumens && <p>{checkLumens()}</p>}
</div>
);
};
export default Measurement;