I'm trying to conditionally return different divs with this function (first time using React).
currUser().played.forEach(square => {
if (square === id) {
console.log(0)
return (
<div className="inactive">
</div>
);
};
});
return (
<div className="square">
</div>
);
}
0 gets logged a few times, but all outputs are of class "square". How do I fix this?
CodePudding user response:
I'm not sure that if you also want to render the div with className="square", if YES then the correct way to do this should be like this:
return (
<>
{currUser().played.filter(square => square === id)
.map(square => (
<div className="inactive">
</div>
)}
<div className="square">
</div>
</>
)
First, you have to filter out you required elements then chain it with map to return and render out the desired elements.
map can't be used with if condition because map should always return something in each iteration. And if you really want to use if condition map then you must also return something in else
Here curly braces are used to run javascript inside JSX.
CodePudding user response:
You should be using the map
method in order to output an array of element. Like so:
return (
<div>
currUser().played.map(square => {
if (square === id) {
console.log(0)
return (
<div className="inactive">
</div>
);
};
return (
<div className="square">
</div>
);
})
</div>
)