Home > Blockchain >  React side panel transforming is not happening
React side panel transforming is not happening

Time:11-16

I have created a custom sidepanel that pops up from the right side and closed on click of outside of the panel. The transition effect when opened and closed is not happening. Can someone help me with this? Help will be really apppreciated

import React, { useState } from "react";
import ReactDOM from "react-dom";
import SlideDrawer from "./SlideDrawer.jsx";

function App() {
  const [drawerOpen, setDrawerOpen] = useState(false);
  return (
    <div>
      {drawerOpen ? (
        <SlideDrawer show={drawerOpen} {...{ setDrawerOpen }} />
      ) : null}
      <button
        onClick={() => {
          setDrawerOpen(!drawerOpen);
        }}
      >
        Click me!
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Sandbox: https://codesandbox.io/s/react-slider-demo-bpi83t?file=/src/index.js:0-558

CodePudding user response:

This is working now, here are the snippets of your components and below a proper explanations of why it wasn't working.

SlideDrawer.jsx

import React, { useEffect, useRef } from "react";
import "./SlideDrawer.css";

export default function SlideDrawer({ setDrawerOpen, show }) {
  const sideMenuRef = useRef(null);

  const onOutsideClick = e => {
    if(sideMenuRef.current && !sideMenuRef.current.contains(e.target) && show) {
      setDrawerOpen(false)
    }
  }

  useEffect(() => {
    document.addEventListener("click", onOutsideClick);
    return () => document.removeEventListener("click", onOutsideClick);
  }, [show, sideMenuRef]);

  return (
    <div ref={sideMenuRef} className={`side-drawer ${show ? 'open' : ''}`}>
      <h1>Hello, I'm sliding!</h1>
    </div>
  );
}

index.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import SlideDrawer from "./SlideDrawer.jsx";

function App() {
  const [drawerOpen, setDrawerOpen] = useState(false);
  return (
    <div>
      <SlideDrawer show={drawerOpen} setDrawerOpen={setDrawerOpen} />
      <button
        onClick={() => setDrawerOpen(!drawerOpen)}
      >
        Click me!
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Explanation

In index.js you were conditional rendering in this part:

{drawerOpen ? (
    <SlideDrawer show={drawerOpen} {...{ setDrawerOpen }} />
) : null}

So the component was being created every time that drawerOpen change.

This portion of code verifies if the click was done inside the drawer so you can close whenever it's outside.

const onOutsideClick = e => {
    if(sideMenuRef.current && !sideMenuRef.current.contains(e.target) && show) {
      setDrawerOpen(false)
    }
  }

Edit:

I change the SlideDrawer component using refs logic.

Hope it helps!

  • Related