moneyoceanswag
moneyoceanswag

Reputation: 11

Pass callback function from parent component to child component react

GOAL: Send callback function from parent to child to toggle sidebar component.

This code opens the sidebar:

<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?

Upvotes: 0

Views: 9577

Answers (1)

jean182
jean182

Reputation: 3505

To change the parent state from a child component you can pass a callback to the child as a prop that sets the state using the setStatus function like this:

<Sidebar show={status} onSidebarClick={() => setStatus(!status)} />

And in your sidebar component you just need to do this:

const Sidebar = ({ show, onSidebarClick }) => {
  // Your code

  return (
   {/* Rest of your JSX */}
    <button onClick={onSidebarClick}>Back</button>
  )
}

You should pass the callback function from the parent and use the setStatus function to perform the change. Do not try to do the change by yourself without the setStatus function.

Upvotes: 3

Related Questions