1

i am trying to make a context with hooks in react in typescript like this:

interface SettingsStateContextProps {
  sort: string;
  type: string;
  price: string;
  option_full: boolean;
  option_rated: boolean;
  option_free: boolean;
}

export const SettingsStateContext = React.createContext<
  Partial<SettingsStateContextProps>
>({});

export const SettingsStoreProvider:any = ({ reducer, initialState, children }):any => (
  <SettingsStateContext.Provider // ERROR HERE
    value={useReducer(reducer, initialState)}
    children={children}
  />
);

but for some reason i don't know why I cannot declare SettingsStateContext.Provider? I am getting an error message with

'Cannot find namespace 'SettingsStateContext'

How do i fix this?

gpbaculio
  • 5,693
  • 13
  • 60
  • 102

2 Answers2

2

I'm not sure about your second export. There is how i use it:

1) Export your context to use it anywhere

import React, { useEffect } from 'react'
import { ThemeProvider } from 'styled-components'

// this is needed so that components using theme will see it's type
declare module 'styled-components' {
  interface DefaultTheme extends Theme {}
}

interface Theme {
  color: string
}

const defaultTheme = { color: 'red' }

export const ThemeContext = React.createContext<Partial<Theme>>({})

export const ThemeContextProvider = props => {
  const [theme, setTheme] = useState<Theme>(defaultTheme)

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

2) Wrap component where you want to get theme access (i use it one time at top level of app):

import React from 'react'
import { ThemeContextProvider, Input } from '@frontend'

export const App = () => {
  return (
    <ThemeContextProvider>
        <Input />
    </ThemeContextProvider>
  )
}

Use it in component (example for shared component):

import styled from 'styled-components'
import React, { forwardRef } from 'react'

type MyProps = {
  err?: boolean
}

export const Input = forwardRef<HTMLInputElement, MyProps>(({ err, ...rest }, ref) => {
  return <StyledInput {...rest} ref={ref} />
})

const StyledInput = styled.input<MyProps>`
  box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
  border-radius: 5px;
`
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
1

I'm seein' here you didn't put any square bracket after React.createContent, you should put write like this React.createContext(),

export const SettingsStateContext = React.createContext();

put your logic in squre bracket, I should work!

you can study here to learn more about!

Thanks!

Ericgit
  • 6,089
  • 2
  • 42
  • 53