I have problem that when my code auto refreshes after I saved the file on VS Code, theText
and theBtn
returns the targeted elements and the page displays the content and everything works fine. But whenever I refresh the page manually, the page displays the content, but when I clicked theBtn
element to expand the text, the theText
and theBtn
becomes empty and the page failed with an error saying “cannot read property of undefined”.
I have been trying to find why, but I could not. Someone please help.
Thank you.
import { React, useEffect, useState } from 'react';
import places from '../data/places';
const Tours = () => {
return (
<>
<div className="my-20 mx-auto bg-blue-100 " style={{ height: "100%" }}>
<h1 className="text-5xl capitalize text-center font-semibold">our tours</h1>
<hr className="w-20 place-self-center mx-auto border-2 mb-12 mt-2 border-green-600" />
<Tuor cTime={new Date().getTime().toString()} />
</div>
</>
)
}
const Tuor = (props) => {
const [tuors, setTours] = useState(places);
const theText = document.querySelectorAll(".theText")
const theBtn = document.querySelectorAll(".theBtn")
console.log(theText);
console.log(theBtn);
const expandText = (index) => {
if (theBtn[index].innerHTML === "read more") {
theText[index].style.maxHeight = "50rem";
theBtn[index].innerHTML = "show less";
} else if (theBtn[index].innerHTML === "show less") {
theText[index].style.maxHeight = "6rem";
theBtn[index].innerHTML = "read more";
}
}
const removePlace = (id) => {
const newTours = tuors.filter((place) => {
return place.id !== id;
});
setTours(newTours);
}
return (
<>
{
tuors.map((place, index) => {
let price = new Intl.NumberFormat().format(place.price);
return (
<>
<div key={index} className="flex flex-col w-2/4 mx-auto bg-white shadow-2xl mb-10">
<div>
<img src={place.image} alt={place.title} />
</div>
<div className="flex mt-10">
<div className="flex justify-start w-3/4 pl-10">
<p className="tracking-widest capitalize font-bold">{place.title}</p>
</div>
<div className="flex justify-end w-1/4 pr-10"><p className="bg-blue-50 tracking-wider p-1 rounded-lg font-bold text-blue-400">N{price}</p></div>
</div>
<div className="my-5 px-10 py-2">
<p className="text-gray-500 theText">{place.description}</p><button className="text-blue-500 capitalize theBtn" onClick={() => expandText(index)}>read more</button>
</div>
<button className="ring-1 ring-red-600 text-red p-1 rounded-sm w-48 mx-auto capitalize my-12" onClick={() => removePlace(place.id)}>not interested</button>
</div>
</>
)
})
}
</>
)
}
export default Tours;