React: TypeError: Cannot read properties of null (reading 'useContext') when trying to use react-bootstrap container

Viewed 8540

As stated in the title I am trying to create a layout component but using any react-bootstrap components seems to give me errors. In this case, using I get the error:

TypeError: Cannot read properties of null (reading 'useContext')

The code for this Layout component is below:

import React from 'react';
import { Container } from 'react-bootstrap';

export const Layout = (props) => (
    <Container>
        {props.children}
    </Container>
    )

And this is being called from App.js below:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Layout } from './components/Layout';
import { Home } from './components/Home';

import './custom.css'

class App extends Component {
  render () {
    return (
        <Layout>
            <Switch>
                <Router>
                    <Route exact path='/' component={Home} />
                </Router>
            </Switch>
      </Layout>
    );
  }
}

export default App;

Replacing the container tags with div renders as expected but any use of react-bootstrap causes the useContext error.

4 Answers

I think the issue is how you import it.

import Container from 'react-bootstrap/Container'

One possible reason of such error is to have multiple version of react. This can be checked by a command like find . -name react.

A second (and unintended) version of react could be introduced as transitive dependencies, or from some tricky package resolution process.

How to eliminate multiple versions depend on the package manager you use. npm has package.json overrides and npm dedup, yarn has resolutions, and so on.

I got the same error, I fixed that by updating my bootstrap version.

Related