javascriptreactjsreact-router-dom

Uncaught TypeError: Cannot read properties of null (reading "useRef")


I am working on a React project, and everything works fine. Then I started using react-router-dom, but the router is not working. I want to go to homescreen but it gives me these errors instead:

Invalid hook call. Hooks can only be called inside of the body of a function component. 
Uncaught TypeError: Cannot read properties of null (reading "useRef")

enter image description here

app.js:

import Container from 'react-bootstrap/Container'
import Footer from './components/footer';
import Header from './components/header';
import './index.css';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import HomeScreen from './screens/homeScreen';

function App() {
  return (
    <Router>
      <Header/>
      <main className='py-3'>
        <Container >
        <Route path="/" exact component={HomeScreen} />
        </Container>
      </main>
      <Footer/>
    </Router>
  );
}

export default App;

HomeScreen.js:

import React from 'react'
import products from '../products'
import {Row, Col} from 'react-bootstrap'
import Product from '../components/product'

function homeScreen() {
  return (

    <div>
       <h1>Latest Products</h1>
        <Row>
            {products.map(product =>(
                <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                  <Product product={product} />
                </Col>
            ))}
        </Row>
     
            
    </div>
  )
}

export default homeScreen

Solution

  • First of all, look inside your package.json file to make sure every used library is listed either as "dependencies" or devDependencies. If not, install them individually.

    In your case, if you are not seeing react-router-dom, open a terminal in the root folder of your project where package.json is, and run:

    npm install react-router-dom
    

    If the issue persists, make sure your Node.js version is not superior to the last recommended one. If not, downgrade it, and for that, you could use n package from npm:

    # if one of the commands does not pass, you may need to use sudo
    npm i -g n
    n stable
    # delete node_modules and start over
    rm -rf node_modules
    npm install
    

    Finally, ensure all your components start with a capital letter, HomeScreen and not homeScreen. And change the component property of Route to element if you are using the version 6 of React Router Dom:

    <Route path="/" exact element={<HomeScreen/>} />