Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 588
Alexohzo Avatar asked May 31 '26 03:05

Alexohzo


1 Answers

Router must be above Switch:

<Router>
    <Layout>
        <Switch>
            <Route path="/" component={Home} />
        </Switch>
    </Layout>
</Router>

https://codesandbox.io/s/determined-zeh-r3vvl4

like image 199
Igor Gonak Avatar answered Jun 02 '26 17:06

Igor Gonak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!