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;
CodePudding user response:
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;
CodePudding user response:
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;
CodePudding user response:
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();