简体   繁体   中英

How to hide sidebar in React using Ant Design

I'm trying to do a sidebar that hides on the clicking of an icon in the navigation bar. And I don't want to use classes, maybe I'm wrong doing it this way, but I want to keep it as much as possible. I've got an error that says:

(property) collapsed: boolean ';' expected.ts(1005)

In the const toggle:

const state = {
    collapsed: true
  };

const toggle = () => {
    state.collapsed: !state.collapsed
};


const Sidebar = () => {

  return (
    <Layout.Sider collapsed={state.collapsed} style={{ backgroundColor: '#f0f0f0' }}>
     ...
    </Layout.Sider>
  )
}

In the navigation bar I got this:

<Button
            type="primary"
            shape="circle"
            icon="user"
            size={'small'}
            style={{ marginLeft: '10px' }}
            onClick={() => toggle}
          />

My layout:

const Layout = ({ children }: LayoutProps) => {
  return (
    <AntdLayout>
      <AntdLayout>
        <Header />
      </AntdLayout>
      <div>{children}</div>
      <Sidebar />
    </AntdLayout>
  )
}

Thank you all!

There are two things what I found as an issue in your code. If you have functional component, you can use useState for updating boolean state. The other one is how you use onClick={() => toggle} , technically you are not calling the function, just returning.

I think you can try the following - creating a boolean variable with state hook:

const Sidebar = () => {
   const [collapsed, setCollapsed] = useState(true);

   return (
      <Layout.Sider collapsed={state.collapsed} style={{ backgroundColor: '#f0f0f0' }}>
         ...
      </Layout.Sider>
   )
}

And in the button, you can use as the following - toggling the value of collapsed variable:

<Button type="primary"
        shape="circle"
        icon="user"
        size={'small'}
        style={{ marginLeft: '10px' }}
        onClick={() => setCollapsed(!collapsed)} />

Read further here:

  1. State hook
  2. Function and Class components

If you are interested in further, I have prepared earlier a repository on GitHub to present toggling elements in class, functional or styled components. Find it here: norbitrial/react-toogle-class-on-click

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM