Emerson P. Ballen
Emerson P. Ballen

Reputation: 145

How to use React.createContext() with react router?

I am trying to use React.createContext() with react router but at the moment has been impossible.

const Context = React.createContext()

<Context.Provider value={{ valueTest: 1 }}>
  <HashRouter>
    <Switch>
      <Route
        exact
        path="/"
        render={() => <h1>HelloWorld</h1>} />
    </Switch>
  </HashRouter>
</Context.Provider>

I always get this error

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

Can someone help me?

Upvotes: 2

Views: 4680

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281932

It seems like an issue rendering your context value, the following code works well

index.js

import React from "react";
import { render } from "react-dom";
import { HashRouter, Switch, Route } from "react-router-dom";
import Hello from "./Hello";
import { Context } from "./context";
const App = () => (
  <Context.Provider value={{ valueTest: 1 }}>
    <HashRouter>
      <Switch>
        <Route
          exact
          path="/"
          render={props => <Hello {...props} name="CodeSandbox" />}
        />
      </Switch>
    </HashRouter>
  </Context.Provider>
);

render(<App />, document.getElementById("root"));

context.js

import React from "react";
export const Context = React.createContext();

Hello.js

import React from "react";
import { Context } from "./context";

export default ({ name }) => (
  <Context.Consumer>
    {value => (
      <h1>
        Hello {name} {value.valueTest}!
      </h1>
    )}
  </Context.Consumer>
);

Working codesandbox

Upvotes: 3

Related Questions