0

I'm following Advanced React Component Patterns on egghead and

I'm having a lot of problems

typing the function inside ToggleContext.Consumer :

interface IContextProps {
  on: boolean;
  toggle?: (flag: boolean) => void;
}
const ToggleContext = React.createContext<IContextProps | undefined>(undefined)

class Toggle extends React.Component {
  static On = ({children}:{children:React.ReactNode}) => (
    <ToggleContext.Consumer>
      {({on}) => (on ? children : null)}
    </ToggleContext.Consumer>
  )
  state = {on: false}
  toggle = () =>
    this.setState(
      ({on}) => ({on: !on}),
      () => this.props.onToggle(this.state.on),
    )
  render() {
    return (
      <ToggleContext.Provider
        value={{on: this.state.on, toggle: this.toggle}}
      >
        {this.props.children}
      </ToggleContext.Provider>
    )
  }
}

How is the way please?

UPDATE

I'd like to know how to type the function inside ToggleContext.Consumer

<ToggleContext.Consumer>
      {({on}) => (on ? children : null)}
</ToggleContext.Consumer>

1 Answer 1

1

It's not really clear on which part you are facing the typing problem from your question, but here is an example that probably will help with typing for your class component.

import React from 'react'

interface IContextProps {
  on: boolean
  toggle?: (flag: boolean) => void
}

interface ToggleProps {
  onToggle: (on: boolean) => void
}

const ToggleContext = React.createContext<IContextProps | undefined>(undefined)

class Toggle extends React.Component<ToggleProps> {
  static On = ({ children }: { children: React.ReactNode }) => (
    <ToggleContext.Consumer>{(ctx) => (ctx?.on ? children : null)}</ToggleContext.Consumer>
  )
  state = { on: false }
  toggle = () => {
    const { on } = this.state
    this.setState({ on: !on })
    this.props.onToggle(on)
  }

  render() {
    return (
      <ToggleContext.Provider value={{ on: this.state.on, toggle: this.toggle }}>
        {this.props.children}
      </ToggleContext.Provider>
    )
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply I've updated the post I'd like to type the function inside ToggleContext.Consumer {({on}) => (on ? children : null)}
cool, so you cant use {on} as your context value since there is possibility it is undefined as been specified here (< IContextProps | undefined>). Therefore, you should have something like this. {(ctx) => (ctx?.on ? children : null)}

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.