Reputation: 806
In my react app, I am returning data from which contains texts of varying lengths.
const ReturnedProducts = () => {
const textStyle = {
maxWidth: '100%',
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
WebkitLineClamp: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
marginBottom: '10px',
};
//This function returns the correct style to the above div.
function calculateTextStyle() {
return truncate ? textStyle : null;
}
// Manage if the text should be truncated or not.
const [truncate, setToggleTruncate] = React.useState(true);
// Function to toggles the state variable 'truncate', thereby expanding and truncating the text when the user clicks the div.
function toggleTruncate() {
setToggleTruncate(!truncate);
}
return (
<div>
<AreaWrapper>
<InnerWrapper>
{data.data.products &&
products.map(product => (
<ProjectCard key={product.id}>
<img src={product.image} alt="test" />
<ProjectCardTitle
onClick={toggleTruncate}
style={calculateTextStyle()}
>
{product.title}
</ProjectCardTitle>
<ProjectButton>
{product.description}
</ProjectButton>
</ProjectCard>
))}
</InnerWrapper>
</AreaWrapper>
</div>
);
};
export default withRouter(ReturnedProducts);
The expand function works fine, however, when I click a single card on the page, the text expands for all cards. How can I make it so that only the clicked card expands? Thanks in advance.
Upvotes: 0
Views: 24
Reputation: 13588
because you are setting truncate to just true/false. u should set it to the product.id
function toggleTruncate(value) {
setToggleTruncate(value);
}
modify your component to use product.id instead
<ProjectCardTitle
onClick={() => toggleTruncate(product.id)}
style={ truncate === product.id ? textStyle : null }
>
Upvotes: 1