score:20
You need to have a Provider that wraps your App before you try to access the context values. In order to have a global and single provider, you need to export wrapRootElement
instance from the gatsby-browser.js file. It would look like
MenuContext.js
import React, { createContext, useState } from "react"
export const MenuContext = createContext()
export const MenuProvider = ({ children }) => {
const [active, setActive] = useState(true);
return (
<MenuContext.Provider value={{active,setActive}}>
{children}
</MenuContext.Provider>
);
};
gatsby-browser.js
import React, { useState } from 'react';
import MenuContext from './src/context/MenuContext';
const wrapRootElement = ({ element }) => {
return (
<MenuProvider>
{element}
</MenuProvider>
);
};
export { wrapRootElement }
Now you could use it within Layout
like
import React, { useContext } from "react"
import { Menu } from "../components/menu"
import { MenuContext } from '../menuContext';
const Layout = ({ children }) => {
const {active} = useContext(MenuContext)
return (
<>
<h1 style={{color:`#fff`}}>{(active) ? `Menu Opened` : `Menu Closed`}</h1>
<main>{children}</main>
<Menu />
</>
)
}
export default Layout
and within Menu
you would have
import React, { useContext } from "react"
import { MenuContext } from '../context/MenuContext';
const Menu = (props) => {
const {active, setActive} = useContext(MenuContext)
const clickHandler = () => {
setActive(!active);
}
return(
<div className={(active ? `open` : `close`)} onClick={clickHandler}></div>
)
}
export { Menu }
Note: You need to create and export the context from a separate file to avoid any circular dependency
However, what you want to achieve can be done without the use of context provided you just to communicate between layout and Menu by lifting the state up to the Layout component
Menu.js
import React from "react"
const Menu = ({clickHandler, active}) => {
return(
<div className={(active ? `open` : `close`)} onClick={clickHandler}></div>
)
}
export { Menu }
Layout.js
import React, {useState} from "react"
import { Menu } from "../components/menu"
const Layout = ({ children }) => {
const [active, setActive] = useState(1)
const clickHandler = () => {
setActive(!active);
}
return (
<>
<h1 style={{color:`#fff`}}>{(menuActive) ? `Menu Opened` : `Menu Closed`}</h1>
<main>{children}</main>
<Menu clickHandler={clickHandler} active={active}/>
</>
)
}
export default Layout
Source: stackoverflow.com
Related Query
- How to use React Context with useState hook to share state from different components?
- How to use callback with useState hook in react
- Updating Parent Component State from Child Component with UseState React Hook
- How to use useEffect hook properly with array dependency. I passed state from redux store and still my component renders infinitely
- How to use useState hook in React with typescript correctly?
- How to delete objects from react state hook array with a button click
- React - useState Hook with Context Api - can't copy a state array to another state array
- Updating state from an array with react useState hook
- How to create a static variable from a state variable made with useState hook on ReactJS?
- How to get only one set state function from use state or some other hook React JS,
- React with TypeScript: how to type useState hook with previous state
- In Next.js, how can I update React Context state with data from getServerSideProps?
- How to use useState hook with array state for children that call the setter function without infinite rendering loop?
- How to change a value from parent component in a child component with useState React hook
- How to use React context on search input and share the input with other components?
- How get multiple values from checkbox list into state using React useState hook
- How to alter state with information from clicked item using React Context API
- How to use React useRef hook with typescript?
- How to use context api with react router v4?
- How to prevent race conditions with react useState hook
- How do I use local state along with redux store state in the same react component?
- How to use React Hooks Context with multiple values for Providers
- How to share React context state across separately mounted component trees
- How to use a different delay for each item with React transition group?
- React 16.4 enables getDerivedStateFromProps to be called from state change. How to cope with that?
- how can I test if useState hook has been called with jest and react testing library?
- Set multiple state values with React useState hook
- Better way to use useState hook for setting the boolean state in React
- How to use the useState hook with asynchronous calls to change an array?
- How does React useState hook work with mutable objects
More Query from same tag
- React "document not defined" when including script
- How to render a React component with survey.js?
- How to correctly reverse a boolean with the ! operator
- Material Grid refused to lay out horizontal even it's default behavior
- Have created a react app (using npx create-react-app) which is getting crash on refresh
- Nextjs API POST request body not being parsed
- Calling react context prop (function) from components function
- How to change stepper color with hooks (Material UI)
- Can I autofocus on the first field in a redux-form created using a loop?
- NextJS Element type is invalid
- Why do semicolons throw error in react JSX?
- React: Map function with two parameters
- Uncaught Error: Target container is not a DOM element. (React webpage won't show anything)
- How to filter from Observable Map in React?
- Passing implementations of generic types to React component props
- React - use Link to and pass data to new component
- UseEffect function to update a state variable
- how to pass props down using map
- How to fix closure in react when using addEventListener and useState
- How to query markdown files of a specific language in Gatsby?
- Reactjs Looping and Adding Conditional Elements within Loop
- Next.js Query param get lost on page refresh
- What is the canonical React-Redux method to pass elements/references between atomic components?
- ReactJS giving error Uncaught TypeError: Super expression must either be null or a function, not undefined
- How to extends material-ui component
- How to get id/params to redux action from react Router?
- redux-thunk dispatch events
- Material-Table : TypeError: Object(...) is not a function Module../node_modules/@material-ui/pickers/dist/material-ui-pickers.esm.js
- Pass parameters of a form to a REST API in React
- Ipfs-http-client isn't a recognized Module in my react app