简体   繁体   中英

Trigger Sidebar from two different button using State in React && styled-components

The first button:

const [open, setOpen] = useState(false);
  return (
    <>
      <SideCart open={open} />
      <CartButton open={open} onClick={() => setOpen(!open)}>
      )
    </>

The sidebar:

const [hide, setHide] = useState(open ? true : true);
  return (
    <SidecartContainer open={open} hide={hide}>

       // Thats the second button 
       // I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>
    </SidecartContainer>

const SidecartContainer = styled.div`
  transform: ${({ open, hide }) =>
    open && hide ? "translateX(0)" : "translateX(100%)"};
`;

I have one button triggering the Open state of sidebar and when it opens I have an x button to close the sidebar.

It only works once.

What shall I use so whenever I click the open button to open and then when I click on close to hide?

It's made with styled-components.

I think your problem is that this line const [hide, setHide] = useState(open? true: true); only runs once on component mount. What you need is a useEffect in the sidebar to listen for changes to open and apply them to the hide state like so:

const [hide, setHide] = useState(open ? true : true);

useEffect(() => {
  setHide(!open);
}, [open]);

  return (
    <SidecartContainer open={open} hide={hide}>

--------Thats the second button 
--------I want to close the sidebar component with this button
      <ExitButton hide={hide} onClick={() => setHide(!hide)}>


    </SidecartContainer>

I finally found what's the right way to do it and it works.

First I declared outside of the sidebar the useStates logic:

  const [open, setOpen] = useState("");
  const hide = () => setOpen("translateX(100%)");
  const show = () => setOpen("translateX(0)");

then I passed the props to Sidecart.js:

const SideCart = (props) => {
  return (
    <SidecartContainer transform={props.transform} open={props.open}>
      <ExitButton open={props.open} onClick={props.onClick}>
        <CloseIcon />
      </ExitButton>
      <ProductCards>
        <CartProductCard />
      </ProductCards>
      <Total></Total>
    </SidecartContainer>
  );
};

also this is important, in the styled component css I declared the prop value:

const SidecartContainer = styled.div`
  transform: ${(props) => props.transform};
`;

Finally I changed the onClick functions accordingly:

  <SideCart transform={open} open={open} onClick={hide} />
  <CartButton open={open} onClick={show}>

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