0

I can't easily reproduce this in a shorter example, but my problem was this:

  1. section is a JavaScript object that is part of state variable array of JavaScript objects which is in the parent module

  2. I can successfully change the value of section.showContent when clicking on the button that calls toggleContent(), but this change would not have any effect on the page.

  3. 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?

enter image description here

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>
            )}
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047
  • [Don't post images of code](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question#:~:text=You%20should%20not%20post%20code,order%20to%20reproduce%20the%20problem)... you're mutating the state. Don't ever mutate state in React, else you'll encounter unexpected behavior like this – CertainPerformance Apr 05 '21 at 17:50
  • The component will re-render when its state is changed, not when it is mutated, even less when the props are mutated. Do you need the parent to know about changes in `showContent`? – Nadia Chibrikova Apr 05 '21 at 17:52

0 Answers0