Search code examples
javascriptreactjsaccordionslide

Make buttons slide up in accordion in React


I have in React an accordion with buttons that slide up/down content, like on this image

I made some functional components and things look like this:

<SlideButtonContainer>
    <SlideButton title="Title goes here">
        Content goes here
    </SlideButton>
    <SlideButton title="Title goes here">
        Content goes here
    </SlideButton>
</SlideButtonContainer>

Clicking a SlideButton calls a function handleClick that changes the state opened of the component, making it slide its content up on false or down on true.

But how could I make all the other SlideButtons inside SlideButtonContainer set their state opened to false?

SlideButton uses SlideDown from this repo and is as follows:

export default function SlideButton(props) {
    const [opened, setOpened] = useState(false);

    function handleClick() {
        setOpened(!opened);
    }

    return (
        <div className="slideButton">
            <div className="slideButtonButton" onClick={handleClick}>
                <div>
                    {props.title}
                </div>
            </div>
            <div className="slideButtonContents">
                <SlideDown>
                    {opened ? props.children : null}
                </SlideDown>
            </div>
        </div>
    );
}

SlideButtonContainer is just a styled div

export default function SlideButtonContainer(props) {
    return (
        <div className="slideButtonContainer">
            { props.children }
        </div>  
    );
}

Solution

  • Solved. In SlideButtonContainer I use React.cloneElement on render and set refs to its children, and I can use children's function with this loop:

    for (var ref in this.refs) {
        this.refs[ref].slideUp();
    }