Artiom O
Artiom O

Reputation: 475

React Router: Invalid hook call. Hooks can only be called inside of the body of a function component

I have a normal react app, using react router. When trying to get the url params in Box.js, I get this error: Invalid hook call. Hooks can only be called inside of the body of a function component. This is the code:

Box.js

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box();

App.js

import
{
  Routes,
  Route
} from "react-router-dom";
import Box from './Box';
function App()
{
  return (
    <div className="App">
      <Routes>
        <Route exact path="/palette/:id/:color" element={<Box />} />
      </Routes>
    </div>
  );
}

export default App;

Upvotes: 0

Views: 217

Answers (3)

alhasan
alhasan

Reputation: 1

If you are using npm link or any other library, your bundler might see two different reacts and show that error see here

or you can remove the ()

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box();

Upvotes: 0

Jamal
Jamal

Reputation: 848

Remove the () from the export part

import React from 'react'
import { useParams } from "react-router-dom";

function Box(){
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box;

Upvotes: 1

Akshay Dhankar
Akshay Dhankar

Reputation: 62

You should not call a function while exporting.

import React from 'react'
import { useParams } from "react-router-dom";

function Box()
{
    let params = useParams();
    return (
        <div>
            <h1>{params}</h1>
        </div>
    )
}
export default Box;

Upvotes: 2

Related Questions