testing495
testing495

Reputation: 272

Passing Components as Props

I'm trying to come up with a generic function to wrap specific contexts around each given page. I'm doing this in my routes section, which will wrap around the state need for a page by page basis. Ideally, this would just be a helper function.

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import Home from "./pages/Home";
import Analytics from "./pages/Analytics";

import { HomeProvider } from "./context/Home";


const wrapPageInContext = (Page, Context) => {
  return (
    <Context>
      <Page />
    </Context>
  );
};

const ContextWrappedHome = () => {
  return (
    <HomeProvider>
      <Home />
    </HomeProvider>
  );
};

export const MainRoutes = () => (
    <BrowserRouter>
      <Switch>
        // This fails! :( 
        <Route
          exact
          path="/home"
          component={wrapPageInContext(Home, HomeProvider)}
        />
        // This works!! 
        <Route
          exact
          path="/home"
          component={ContextWrappedHome}
        />
        <Route exact path="/Analytics" component={<Analytics />
</BrowserRouter>
);

Upvotes: 1

Views: 34

Answers (1)

thedude
thedude

Reputation: 9822

your wrapPageInContext function needs to return a component, like so:

const wrapPageInContext = (Page, Context) => () => {
  return (
    <Context>
      <Page />
    </Context>
  );
};

Or to make this a little more explicit:

const wrapPageInContext = (Page, Context) => {
  const Wrapper = () => (
    <Context>
      <Page />
    </Context>
  )
  return Wrapper
};

Upvotes: 1

Related Questions