How create context with TypeScript (solved)

I want change number in Numbers.tsx component using context Here is codesandbox:https://codesandbox.io/p/sandbox/fancy-resonance-kwr7um SOLUTION How create context (to learn - repeat after this guide) Step 1 - in NumbersContext.tsx file create context
export const NumbersContext = createContext<NumbersContextType>({
number: "1",
setNumber: () => null,
});
export const NumbersContext = createContext<NumbersContextType>({
number: "1",
setNumber: () => null,
});
Step 2 - write types for Context
type NumbersContextType = {
number: string;
setNumber: React.Dispatch<React.SetStateAction<string>>;
};
type NumbersContextType = {
number: string;
setNumber: React.Dispatch<React.SetStateAction<string>>;
};
type for setNumber check here - https://prnt.sc/J7akV_6AoQcW Step 3 - write provider for context
export function NumbersProvider({ children }: NumbersProviderProps) {
const [number, setNumber] = useState<string>("1");

return (
<NumbersContext.Provider value={{ number, setNumber }}>
{children}
</NumbersContext.Provider>
);
}
export function NumbersProvider({ children }: NumbersProviderProps) {
const [number, setNumber] = useState<string>("1");

return (
<NumbersContext.Provider value={{ number, setNumber }}>
{children}
</NumbersContext.Provider>
);
}
Step 4 - in provider describe props (by default its only children) https://prnt.sc/qvHRZUmGtoRp
interface NumbersProviderProps {
children: React.ReactNode;
}
interface NumbersProviderProps {
children: React.ReactNode;
}
or you can simplify it like so (do it if you have only 1 prop) https://prnt.sc/rF5jzuY6zytI Step 5 - write default values for context https://prnt.sc/YoQcFrv8cKQ8 Step 6 - wrap in ContextProvider values that you want to use https://prnt.sc/vdxoYaF3oaMm Step 7 - use your context like this https://prnt.sc/Bikfo252H16g At the end: 1)You create provider form context I mean this https://prnt.sc/2bD0SN7gp0m5 2)And to use values from context you use useContext(NumbersContext) To wrap something that you want to use with context you use NumbersProvider I had this mistake https://prnt.sc/QYsIK97EW5Ob I thought that I wrap all in provider but function App3 was not it the provider like this https://prnt.sc/ov1EF9YYNKs8 3)Also if you use a lot of contexts its better to create index file https://prnt.sc/LK54ZJc5lVe8 Codesandbox:https://codesandbox.io/p/sandbox/context-ts-forked-5lwwxr
1 Reply
Nikita
NikitaOP2y ago
Please send me working codesandbox where I can change number in Numbers.tsx using context
Want results from more Discord servers?
Add your server