0

I just cannot figure this one out. I think it's to do with how I set my state in the 'toggleTheme' function. I'm sorry if I don't fit the styling for a post, I find I always make an oversight. Also, I have looked through the similar questions and tried their solutions but for some reason it just still will not work. I've actually made the project in codesandbox but I don't know how to make it a non live link, ugh.

To quickly elaborate, I'm trying to turn my ThemeContextProvider class into a functional component, but when I try to do the toggleTheme to switch from light to dark and vice versa, it will throw a myriad of errors saying one of my variables I reference is not there. Ugh I'm overwhelmed :(

The working code:

import React, { createContext, Component } from 'react';

export const ThemeContext = createContext();

class ThemeContextProvider extends Component {
  state = {
    isLightTheme: true,
    light: { syntax: "#48527d", ui: "#a997af", bg: "#cee7e4" },
    dark: { syntax: "#bbbccf", ui: "#7b8ab2", bg: "#48527d" }
  }

  toggleTheme = () => {
    this.setState({ isLightTheme: !this.state.isLightTheme});
  }

  render() {
    return (
      <ThemeContext.Provider value={{...this.state, toggleTheme: this.toggleTheme}}>
        { this.props.children }
      </ThemeContext.Provider>
    );
  }
}

export default ThemeContextProvider;

This code will work as seen in the screen shots I posted on imgur link

When I change it to a functional component, I have a myriad of errors, which is shown in the imgur link at the top or bottom of the page:

import React, { createContext, Component, useState } from "react";

export const ThemeContext = createContext();

const ThemeContextProvider = (props) => {
  const [theme, setTheme] = useState({
    isLightTheme: true,
    light: { syntax: "#48527d", ui: "#a997af", bg: "#cee7e4" },
    dark: { syntax: "#bbbccf", ui: "#7b8ab2", bg: "#48527d" },
  });

  const toggleTheme = () => {
    setTheme({
      isLightTheme: !theme.isLightTheme,
    });
  };

  return (
    <ThemeContext.Provider value={{ ...theme, toggleTheme: toggleTheme }}>
      {props.children}
    </ThemeContext.Provider>
  );
};

export default ThemeContextProvider;

I cannot figure out why it's throwing these errors. Perhaps I'm not thinking hard enough about it but I'm starting to lose it a little bit here.

I'm going to re-list the resources for convenience here at the bottom:

Interactable Code: codesandbox

Screenshots of outcomes and errors: link

spongurat
  • 13
  • 2
  • Either spread the existing object into the new state, or (better) separate the states out into different variables, or (even better) since it doesn't look like you're ever changing the `light` or `dark` properties, move them out of state entirely – CertainPerformance Jun 02 '22 at 03:01

0 Answers0