Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a sidebar the toggles on and off. Currently, when I use the following code, the side bar opens as expected:

<Sidebar show={status} />

  <button onClick={() => setStatus((status) => !status)}>
      <SettingsIcon/>
  </button>

I use both true and false values for status to toggle the sidebar on and off.

Now, in my sidebar component, I need to pass a false value to show so that is closes when my Back button is clicked.

const Sidebar = ({ show }) => {
  const { left } = useSpring({
    from: { left: "-100%" },
    left: show ? "0" : "-100%",
  });

  return (
    <animated.div
      style={{
        left: left,
        position: "absolute",
        height: "100%",
        width: "55%",
        backgroundColor: "black",
        zIndex: 1,
      }}
      className="Sidebar"
    >
      <button onClick={() => !show}>Back</button>
      <p>hello</p>
    </animated.div>
  );
};

I can't seem to get it working. Any ideas what I am doing wrong?

question from:https://stackoverflow.com/questions/65893276/pass-child-component-value-back-to-parent-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

You should pass the onClick callback from parent to child and keep the show variable in the parent component.

Parent:

<Sidebar show={status} onClose={() => setShow(!show)} />
    <button onClick={() => setStatus((status) => !status)}>
        <SettingsIcon/>
    </button>
</Sidebar>

Child:

const Sidebar = ({ show, onClose }) => {
  const { left } = useSpring({
    from: { left: "-100%" },
    left: show ? "0" : "-100%",
  });

  return (
    <animated.div
      style={{
        left: left,
        position: "absolute",
        height: "100%",
        width: "55%",
        backgroundColor: "black",
        zIndex: 1,
      }}
      className="Sidebar"
    >
      <button onClick={onClose}>Back</button>
      <p>hello</p>
    </animated.div>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...