I can't easily reproduce this in a shorter example, but my problem was this:
section
is a JavaScript object that is part of state variable array of JavaScript objects which is in the parent moduleI can successfully change the value of
section.showContent
when clicking on the button that callstoggleContent()
, but this change would not have any effect on the page.Only when I created another state variable and change the value of that state variable, does the change in
section.showContent
have an effect on the state on my page.
This happens to fix my current problem, but I have no idea why this works.
Can anyone explain it?
interface ICurriculumSectionProps {
section: any;
searchText: string;
sectionIndex: number;
}
function CurriculumSection(props: ICurriculumSectionProps) {
const [message, setMessage] = useState('start');
const { section, searchText, sectionIndex } = props;
const toggleContent = () => {
section.showContent = !section.showContent;
setMessage(`${message}n`); // necessary to make changes in section variable affect React page
};
return (
<li id={section.isToday ? 'today' : ''} key={sectionIndex} className="section">
{(section.formattedDay && (searchText.trim() === '' || (section.bulkSearchText.toUpperCase().includes(searchText.toUpperCase())))) && (
<div className={section.isToday ? 'dayLabel isToday' : 'dayLabel isNotToday'}>
{section.formattedDay}
</div>
)}