Timbo
Timbo

Reputation: 125

Correct way to update react context

I am using the Gatsby, and the layout plugin, so that my navbar can persist, while the page content below it changes. The reason for this is that i want some animations to run as the pages change, so i don't want the navbar to reload mid-animation. I have it working to a basic level, however the animations jump back to start from the same point each time, instead of transitioning from the current state to the next. I realise this is because i need to add the next class before removing the previous, but I am tying myself in knots with the context api to try to achieve this. You can see what i mean in this sandbox: https://codesandbox.io/s/ancient-cookies-tmb5b The problem is with applying the correct classes to this div in components/TopNav:

<div className={`menuBarIcons ${this.props.data.prevPage} ${this.props.data.curPage}`}>

which is contingent on being able to update components/Context.js with both the previous and the current page. The current page part is working, as you can see from the text output on the respective pages (and the animations), but to get the previous page I've tried from componentWillUnmount on the previous page, using prevState and no luck. I have the feeling my approach has become overly complex; any pointers to a solution much appreciated.

Upvotes: 1

Views: 79

Answers (1)

ksav
ksav

Reputation: 20821

You need to use gatsby-browser.js to wrap your root element with your context provider. See https://www.gatsbyjs.org/blog/2019-01-31-using-react-context-api-with-gatsby/

// gatsby-browser.js

import React from "react"
import { ThemeProvider } from "./src/context/ThemeContext"

export const wrapRootElement = ({ element }) => (
  <ThemeProvider>{element}</ThemeProvider>
)

Upvotes: 1

Related Questions