How can a div be shown/hidden when a condition is met in React, when the data comes from a JSON array? I've got this code so far, but when I change the value of isPassed={resultPass.pass}
to isPassed={resultPass.failed}
it still shows the result as pass
.
The closest example I've found is this , but it does not fetch value from a JSON ( var resultPass in my code), but just assigns true/false value to a const.
var resultPass = {
"pass": "passpass",
"fail": "failfail"
}
function Passed(props) {
return <div class="result-pass"><h3>passpass</h3></div>;
}
function Failed(props) {
<div class="result-fail"><h3>failfail</h3></div>;
}
function ResultDisplay(props) {
const isPassed = props.isPassed;
if (isPassed) {
return <Passed />;
}
return <Failed />;
}
// When resultPass.pass is changed resultPass.fail it still shows as pass
render(<ResultDisplay isPassed={resultPass.pass} />, document.getElementById('root'));
Here is my Codesandbox .
That is because if (isPassed) {
always evaluate to true
. You should check the if condition properly like this
if (isPassed === "passpass") {
return <Passed />;
}
return <Failed />;
You're not properly checking the prop of ResultDisplay
.
const isPassed = props.isPassed;
if (isPassed) {
return <Passed />;
}
return <Failed />;
isPassed
will be either the string "passpass" or "failfail", but since your if
statement is making a basic equivalency check, it is type converting both of your strings to a true
boolean value. So, your if
statement always evaluates to true
and you're always returning <Passed />
.
The proper way to check the equivalency of a string is with the more strict identity operator ( ===
) which will not convert type and ensure that you're checking for the exact same string.
const isPassed = props.isPassed;
if (isPassed === "passpass") {
return <Passed />;
}
return <Failed />;
You also need to ensure that your Failed()
function returns something, otherwise it will not work properly.
function Passed(props) {
return <div class="result-pass"><h3>passpass</h3></div>;
}
function Failed(props) {
return <div class="result-fail"><h3>failfail</h3></div>;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.