0

I am planning to implement a theme changer and would like to store the color selected by the user in the context. When I pass data to the value prop of the Context.Provider, I get an error TS2739: Type 'Readonly<{}>' is missing the following properties from type 'ThemeContextType': color, onChangeTheme. Please advice. This is what I have.

class App extends Component {
  private onChangeTheme = (color: string) => this.setState({ color });

  constructor(props: {}) {
    super(props);
    this.state = {
      color: Colors.BLUE3,
      onChangeTheme: this.onChangeTheme,
    };
  }

  public render() {
    return (
            <ThemeContext.Provider value={this.state}>
              <Routes />
            </ThemeContext.Provider>
    );
  }

}

ThemeContext.ts

import { createContext } from 'react';

type ThemeContextType = {
  color: string;
  onChangeTheme: (value: string) => void;
};

export const ThemeContext = createContext<ThemeContextType | undefined>(
  undefined
);

Error Message:

TS2739: Type 'Readonly<{}>' is missing the following properties from type 'ThemeContextType': color, onChangeTheme index.d.ts(337, 9): The expected type comes from property 'value' which is declared here on type 'IntrinsicAttributes & ProviderProps<ThemeContextType | undefined>'

1 Answer 1

1

Your app component doesn't specify the type on its state, so it defaults to {}. Change this:

class App extends Component {

To this:

interface AppState {
  color: string;
  onChangeTheme: (value: string) => void;
}

class App extends Component<{}, AppState> {

Or since that AppState is identical to ThemeContextType, you could do:

class App extends Component<{}, ThemeContextType> {
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I have exactly the same problem but with functional components. I cannot pass the setter function of a usestate to the value in the context provider. many thanks

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.