Ad

How Do I Close And Open My Sidebar OnClick

- 1 answer

Whenever I use it, the side bar is always open even when I didn’t click the button to do so. In other words, whenever I refresh my browser, the side bar is already opened. I want it to be closed, only when I click the button should the side bar open up.

But I want it to open and close on command. I tried playing around with the supported props but still no luck :(.

I'm using this btw https://github.com/balloob/react-sidebar#installation

Here's my App.js file:

import React from "react";
import Sidebar from "react-sidebar";

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sidebarOpen: true
        };
        this.onSetSidebarOpen = this.onSetSidebarOpen.bind(this);
    }

    onSetSidebarOpen(open) {
        this.setState({ sidebarOpen: open });
    }

    render() {
        return (
            <Sidebar
                sidebar={<div><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b><b>Sidebar content</b></div>}
                open={this.state.sidebarOpen}
                onSetOpen={this.onSetSidebarOpen}
                styles={{ sidebar: { background: "white" } }}
            >
                <button onClick={() => this.onSetSidebarOpen(true)}>
                    Open sidebar
                </button>
            </Sidebar>
        );
    }
}

export default App;
Ad

Answer

First, if you want it to start as closed, then initial the value to false ..

    this.state = {
        sidebarOpen: false
    };

Secondly, if you want it to open and close , set onClick normally ->onClick={this.onSetSidebarOpen} :

onSetSidebarOpen() {
    this.setState((prevState) => ({ sidebarOpen: !prevState.sidebarOpen }));
}

In general - of course it stays open, you set the value to true by default, and it stays true for ever.

Ad
source: stackoverflow.com
Ad