So basically I am trying to render map of restaurant cards. However in the div with the classname= {isExpanded ..... I would like the text to be cropped and have a read more link. When clicked it should show the full text of data.description wrapped in the ReadMore function and expand the div using the class names to fit the entire content. The problem is if i leave setIsReadMore in the toggleReadMore on its own it shows the full text when clicked but obviously the text leaks out of the div. When i add the isExpanded to the toggleReadMore it only now alters the size of the div on click but doesnt show the full text. I have tried to console log both values before and after and only the IsExpanded changes from true and false but isreadmore remains always true. Is there a workaround for this? thanks
import React from 'react';
import useFetch from '../useFetch.js';
import {RestaurantBox} from '../styles/bestratedrestaurants.js'
import {Image,NameBox, TopBox, P, P2,BottomBox} from "../styles/reviewsmap.js"
import TestPic from "../assets/london-restaurant.jpeg";
import {Bio,Box,Span} from "../styles/usersMap.js"
import {useState} from 'react';
import '../styles/usermap.css'
const UsersMap = () => {
const {data,isPending, error} = useFetch('http://127.0.0.1:8000/backend/api/users/list/'); //custom hook to fetch data
const [isExpanded,setIsExpanded] = useState(true)
const ReadMore = ({ children }) => {
const text = children;
const [isReadMore, setIsReadMore] = useState(true);
const toggleReadMore = () => {
console.log(isReadMore)
console.log(isExpanded)
setIsExpanded(!isExpanded)
setIsReadMore(!isReadMore)
console.log(isReadMore)
console.log(isExpanded)
};
return (
<p className="text">
{isReadMore ? text.slice(0, 150) : text}
<Span onClick={toggleReadMore}>
{isReadMore ? "...read more" : " show less"}
</Span>
</p>
);
};
return (
<RestaurantBox>
{error && <div>{error}</div>}
{isPending && <div>Loading...</div>}
{data && data.map(data => (
<div className={ isExpanded ? 'expand': 'users' }key={data.id}>
<TopBox>
<Image src={TestPic}></Image>
<NameBox>
<P>{data.first_name} {data.last_name[0]}.</P>
{<P2>6 Reviews in total</P2>}
</NameBox>
</TopBox>
<BottomBox>
<Bio>
<ReadMore>
{data.description}
</ReadMore>
</Bio>
</BottomBox>
</div>
))}
</RestaurantBox>
);
}
export default UsersMap
.users {
margin-top:20px;
width:18%;
height:25%;
min-height:300px;
min-width:300px;
border-radius:3px;
background-color: #FFFFFF;
border-radius:3px;
border-top:5px solid #E47D31;
margin-bottom:25px;
}
.expand{
margin-top:20px;
width:18%;
height:25%;
border-radius:3px;
background-color: #FFFFFF;
border-radius:3px;
border-top:5px solid #E47D31;
margin-bottom:25px;
}
CodePudding user response:
Try to move const [isReadMore, setIsReadMore] = useState(true);
outside your ReadMore
function. React needs that in order to know how to change state and preserve it on re-renders.