2

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.