I am trying to create a context wrapper. Pass the state variables as provider values and try to access those values using useContext
in the ToolBar
component.
type NavContextType = {
isDrawerOpen: boolean;
setIsDrawerOpen: React.Dispatch<React.SetStateAction<boolean>>;
};
export const NavContext = createContext<NavContextType | null>(null);
const NavBar: :ReactFC<ReactNode | undefined> = ({ children }) => {
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
return (
<NavContext.Provider value={{ isDrawerOpen, setIsDrawerOpen }}>
<ToolBar />
</NavContext.Provider>
);
};
Toolbar.js:
import { NavContext } from "./NavBar";
const ToolBar = () => {
const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);
return (
.......
.......
);
};
when I try to access context values using const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);
. I get typescript error as:
TS2339: Property 'setIsDrawerOpen' does not exist on type 'NavContextType | null'.
Property 'isDrawerOpen' does not exist on type 'NavContextType | null'.
Please guide me.
CodePudding user response:
You need to use as
directive for example useContext(NavContext) as NavContextType
. Typescript will know, that the value is not null.