2

I'm trying to toggle element by clicking on button, however it doesn't do anything. Also note that code is simplified as I didn't want to copy whole app, I just included parts I thought are important. Here is code:

  1. Navbar.js ..Here I try to invoke the function it comes from context.js file where I setup my contextAPI

    import { useGlobalContext } from "./context";    
    const { openSidebar, openSubmenu, closeSubmenu } = useGlobalContext();
        <button className="btn toggle-btn" onClick={openSidebar}>
    
  2. context.js

    const AppContext = React.createContext();
    
    const AppProvider = ({ children }) => {
    const [isSidebarOpen, setIsSidebarOpen] = useState(false);
    const openSidebar = () => {
         console.log("test")
         setIsSidebarOpen(true);
     };
    return (
         <AppContext.Provider value={(isSidebarOpen,  openSidebar, closeSidebar)}>
             {children}
         </AppContext.Provider>
     );
    }
    
    export const useGlobalContext = () => {
    return useContext(AppContext);
    };
    
    export { AppContext, AppProvider };
    
  3. App.js

    document.addEventListener("click", (e) => {
     console.log(e);
     console.log(e.target);
    });
    
  4. index.js

    import App from "./App";
    import { AppProvider } from "./context";
    
    
    
    ReactDOM.render(
       <React.StrictMode>
        <AppProvider>
         <App />
        </AppProvider>
       </React.StrictMode>,
       document.getElementById("root")
    );
    

The event listener from App.js displays correctly event and also event.target which is the button. However I don't get any log to console from context.js where it should log "test", not error, not warning, nothing... onClick is completely ignored.

2 Answers 2

1

You will find your answer here

onClick={( )=>{openSidebar( )}}

Sign up to request clarification or add additional context in comments.

4 Comments

well it did run the function indeed, but now I get openSidebar is not a function error ...
Try this onClick={( )=>{openSidebar}}
Expected an assignment or function call and instead saw an expression
I think there must be a problem somewhere in context API where I send my functions as props, I don't know what else could be wrong
0

Okay Ive resolved it, the problem was in parentheses in context.js

here is old code:

return (
 <AppContext.Provider value={(isSidebarOpen,  openSidebar, closeSidebar)}>
     {children}
 </AppContext.Provider>

);

here is new one:

return (
    <AppContext.Provider value={{ isSidebarOpen,  openSidebar, closeSidebar }}>
        {children}
    </AppContext.Provider>
);

I needed to replace () with {}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.