I need my drop-down button to show the text below if I press one, and another one for hiding. I tried to use the useState method, but it also doesn't work, and same with the non-useState method. Here is my code, hope someone can fix this, thanks
function AnnouncementCard(props) {
const { announcement } = props;
const triangleDown = <img src={DropDown} alt="No-img" />;
const triangleUp = <img src={DropDownActive} alt="No-img" />;
function Readmore() {
console.log("inject", currentTriangle);
if (currentTriangle == triangleDown) {
DisplayText(null);
ChangeTriangle(triangleUp);
console.log(2, currentTriangle);
} else if (currentTriangle == triangleUp) {
DisplayText(<Text>{announcement.detail}</Text>);
ChangeTriangle(triangleDown);
console.log(1, currentTriangle);
}
}
const [currentTriangle, ChangeTriangle] = useState(triangleUp);
const [currentText, DisplayText] = useState(null);
return (
<Card>
<CardBody>
<PictureBox>
<Picture src={announcement.img} alt="no-img" />
</PictureBox>
<TextBox>
<Title>{announcement.title}</Title>
<Date>{announcement.date}</Date>
<ReadMore onClick={() => {Readmore();}}>
Read more
<Triangle>{currentTriangle}</Triangle>
</ReadMore>
</TextBox>
</CardBody>
<Textarea>{currentText}</Textarea>
</Card>
);
}
export default AnnouncementCard;
CodePudding user response:
You cannot simply compare JSX elements using ==
operator (currentTriangle == triangleDown
). To make it simple, I would use a boolean instead of saving the element in the state, and depending on that you can show up and down buttons.
- Replace the
ChangeTriangle
state hook with the following.
const [toggleValue, setToggleValue] = useState(true);
- Update the
ReadMore
function as below.
function Readmore() {
if (toggleValue === false) {
DisplayText(null);
setToggleValue(true);
} else if (toggleValue === true) {
DisplayText(<Text>{announcement.detail}</Text>);
setToggleValue(false);
}
}
- Set the triangle button as below using a ternary operator.
<Triangle>{toggleValue ? triangleUp : triangleDown}</Triangle>