< Back

Create context provider in React.js


Solution:

  1. Create a folder ./context in ./src folder.
  2. Create a file ./context/ContextProvider.tsx
  3. In your ContextProvider.tsx file, create a context provider.
Copy ✂️
import {createContext, useState} from "react"; const Context = createContext<any>(null); const ContextProvider = ({children}: any) => { const [ctx, setCtx] = useState<any>({ // Here you'll define your context data text: '', yearStart: '', yearEnd: '', nasaData: [], }); return ( <Context.Provider value={{ctx, setCtx}}> {children} </Context.Provider> ); }; export {Context, ContextProvider};
  1. In your index.tsx file, import the context provider and wrap it around your router.
Copy ✂️
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import reportWebVitals from './reportWebVitals'; import Router from "./router/Router"; import {ContextProvider} from "./context/ContextProvider"; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.StrictMode> <ContextProvider> <Router/> </ContextProvider> </React.StrictMode> ); reportWebVitals();
  1. In your component, import the context and use it.
Copy ✂️
import {Context} from "../context/ContextProvider"; ... const {ctx, setCtx} = useContext(Context); console.log(ctx.text);

You can find an github example here.

🚀 Enjoy!