Search code examples
javascriptreactjsparent-childreact-propsreact-functional-component

ReactJS call parent function from grandchild without using props


Hello I have a program right now where my great-grandchild calls the parent function that is passed down by props. I don't like the idea of passing a function too deep into the component tree. Is there an alternate way of doing this?

I looked into static functions, but I'm not sure how I can do it with functional components.

My component tree looks like this:

App
- resetDisplay() //pass this down
- NavBar
  - ButtonGroup
    - ResetButton 
      - onClick = props.resetDisplay

Solution

  • You can put a function into context just as you would put in a value.

    Here is an example:

    import React, {useContext} from 'react';
    
    const NavbarContext = React.createContext({resetDisplay: () => {}});
    
    function Navbar() {
        function resetDisplay() {
            // do stuff in here
        }
    
        return (
            <NavbarContext.Provider value={{resetDisplay}}>
                <ButtonGroup />
            </NavbarContext.Provider>
        );
    }
    
    
    function ButtonGroup() {
        return (
            <div>
                <ResetButton />
            </div>
        );
    }
    
    function ResetButton() {
        const {resetDisplay} = useContext(NavbarContext);
    
        return <Button onClick={() => resetDisplay()} >Reset</Button>;
    }