skip to Main Content

I want to set an event on Header when an action happened on {children}, how can i do this

function Basic({ children }) {
  return (
    <>
      <Header/>
      {children}
      <Footer />
    </>
  );
}

export default Basic;

I have tried with document event but it didn’t work
{chidren} is an over flow y component and when I scroll on it, I expect event will dispatch to Header

2

Answers


  1. Chosen as BEST ANSWER

    Use React.cloneElement to send data from callback to prop

      function Basic({ children }) {
      const [data, setData] = useState();
    
      return (
        <>
          <Header data={data} />
          {React.cloneElement(children, { sendData: setData })}
          <Footer />
        </>
      );
    }
    

  2. Create a state at the top level and pass it to children and listen for state change.

    // Header.jsx
    
    import { useEffect } from "react"
    
    function Header({ event }) {
        useEffect(() => {
            if (event) {
                // Set Event
                console.log("Event Set")
            } else {
                console.log("Event Removed")
            }
        }, [event])
        return <div>Header</div>
    }
    export default Header
    
    
    // Basic.jsx
    
    import Header from "./Header"
    
    function Basic({ children, event }) {
        return (
            <>
                <Header event={event} />
                {children}
            </>
        )
    }
    
    export default Basic
    
    
    // MainContainer.jsx
    
    import { useState } from "react"
    import Basic from "./Basic"
    
    function Container() {
        const [event, setEvent] = useState(false)
        const handleClick = () => {
            setEvent(!event)
        }
        
        return (
            <Basic event={event}>
                <p>Click on the button</p>
                <button onClick={handleClick}>Click</button>
            </Basic>
        )
    }
    export default Container
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search