Search code examples
javascriptreactjsdomreact-contextreact-dom

How to add AppContext Provider for document body in react?


I want to do like this. How to do this. Add the App context provider for document body. But it should not affect existing content.

ReactDOM.createRoot(document.body).render(
<AppContextProvider>
  {document.body}
</AppContextProvider>
);

Solution

  • An appContextProvider function need to be construct first like below for example

    import { useReducer, createContext, useMemo } from 'react';
    import { initialState, contextReducer } from 'yourOwnReducer';
    
    const AppContext = createContext();
    
    function AppContextProvider({ children }) { 
    const [state, dispatch] = useReducer(contextReducer, initialState);
    const value = useMemo(() => [state, dispatch], [state]);
    
    return <AppContext.Provider value={value}>{children} 
    </AppContext.Provider>;
    }
    
    export default AppContextProvider;
    

    then wrap the app component with the function after importing it

    import React from "react";
    import { BrowserRouter, Route, Routes } from "react-router-dom";
    import { createRoot } from "react-dom/client";
    
    import App from "./app";
    
    import AppContextProvider from "./AppContextProvider";
    
    const root = createRoot(document.getElementById("root"));
    
    root.render(
      <React.StrictMode>
       <BrowserRouter>
        <AppContextProvider>
         <Routes>
          <Route path="/*" element={<App />} />
         </Routes>
        </AppContextProvider>
      </BrowserRouter>
     </React.StrictMode>
    );