React child component not rerendering when parent state array updates


blockClasses is a string array state in the Grid class, and I am passing it as a prop to a subcomponent. blockClasses defines the classNames for the Block component.

When I change the blockClasses state, it does not update the child component (The className remains the same but the state changed.)

I saw someone saying something about using "componentWillReceiveProps," but Typescript says that I cannot use it for some reason.

I tried using "key" as a prop for Block instead of "blockClassNames" but React gives me an error in the console telling me to not use key.

Is there any way I could force the child component to change if the state of the parent changes without using key or componentWillReceiveProps?

Thanks in advance.

Grid/index.tsx

    const [
        blockClasses,
        setBlockClasses
    ] = useState<string[]>(
        [
            "Block Block--item0",
            "Block Block--item1"
        ]
    );

    // ...

    // Function that gets called during runtime that updates blockClasses... (Shortened immensely)
    useEffect(() => {
        swappable.on("swappable:swapped", () => {
            updateClasses();
        });
        
        function updateClasses() {
            for(let i = 0; i < 2; i++) {
                let blockClassName = "Block Block--item" + i;
                
                let tempBlockClasses2 = blockClasses;
                tempBlockClasses2[i] = blockClassName;
                setBlockClasses(tempBlockClasses2);
            }
        }
    });

    return (
        <Wrapper className="BlockLayout">
            <BlockWrapper index={0} >
                <Block
                    // Passing state as prop to child
                    blockClassName={ blockClasses[0] }
                    text={ 0 + "" }
                />
            </BlockWrapper>
            <BlockWrapper index={1} >
                <Block
                    blockClassName={ blockClasses[1] }
                    text={ 1 + "" }
                />
            </BlockWrapper>
    }

Block/index.tsx

// Block is not updating it's className when the parent state changes.
const Block = ( {blockClassName, text}: {blockClassName: string, text: string} ) => {
    return (
        <span className={ blockClassName }>
            <Content>
                <h1>{text}</h1>
            </Content>
        </span>
    );
}

Source: React – Stack Overflow

November 4, 2021
Category : News
Tags: react-component | react-state | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.