How I can use BrowserRouter in React correctly? - javascript

I'm creating a React project and I want to implement the BrowserRouter but the problem is that when I used it, it always throw the React Error of:
***Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.***
I don't know what is this about, because as far as I know, I'm not using hooks and I read the documentation and other tutorials to solve this problem (like deleting double react or npm link and that's stuff) but this still a problem.
Here are my files.
App.js
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";
import Navbar from "./components/navbar"
import Login from "./components/login";
// import CreateExercise from "./components/create-exercise.component";
// import CreateUser from "./components/create-user.component";
function App() {
return (
// <h1>HOASNKFNLSA</h1>
// <div>
// <Home/>
// </div>
<BrowserRouter>
<Routes>
<Route path="/" render={() => {
<h1>HOKAKSFNAKSO</h1>
}}>
</Route>
</Routes>
</BrowserRouter>
);
}
function Home() {
return (
<div className="container text-center">
<h1>KEVIN STYLE PELUQUERIA</h1>
</div>
);
}
function About() {
return (
<div>
<h2>About</h2>
</div>
);
}
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
</div>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
package.json
{
"name": "kevin-style-peluqueria",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I don't know if you need anything else, but if you do, ask me in comments. If you need to know more extra info, I'm not using webpack. I'm using the classic React structure application when you do the command npx create-react-app. I'm also using express and MongoDB like my backend (basically I'm creating an application with the MERN Stack).

You should do something like this.
And take a look to the docs with examples
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter as Router } from 'react-router-dom'
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();

Related

Warning: Please use `require("history").createBrowserHistory` instead of `require("history/createBrowserHistory")`

hi I am getting this warning and I want this warning to be solved and wouldn't be displayed on the console tab so I could upload my code to netlify and as far as I have read the documentation and policies of netlify, it says warnings and errors may be the reason that it can't be uploaded so I need this to be solved
index.js file
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter, Route, Link } from 'react-browser-router';
import "../src/assets/css/index.scss";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
reportWebVitals();
package.json
{
"name": "daryaft-yar",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^1.1.3",
"lodash": "^4.17.21",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-browser-router": "^2.1.2",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-icons": "^4.6.0",
"react-paginate": "^8.1.4",
"react-scripts": "5.0.1",
"sass": "^1.55.0",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
app.js
import './App.css';
import { Switch, Route, Redirect } from 'react-router-dom';
import React, { Component } from 'react';
import Shop from './Components/shop-bot/shop';
import Home from './Components/shop-bot/botHome';
import Coin from './Components/Coin/coin';
import Wallet from './Components/Wallet/wallet';
import AddCoin from './Components/AddCoin/add-coin';
import Cart from './Components/cart/cart';
import FinalCart from './Components/final-cart/final-cart';
import UserForm from './Components/user-from/user-form';
class App extends Component {
componentDidMount() {
}
render() {
return (
<React.Fragment>
<Switch >
<Route path="/bot/shop" component={Shop}/>
<Route path="/bot/home" component={Home} />
<Route path="/bot/coin" component={Coin} />
<Route path="/bot/buy-coin" component={AddCoin} />
<Route path="/bot/wallet" component={Wallet} />
<Route path="/bot/cart" component={Cart} />
<Route path="/bot/cart-final" component={FinalCart} />
<Route path="/bot/user-data" component={UserForm} />
<Redirect from="/" exact to="/bot/shop" />
</Switch>
</React.Fragment>
);
}
}
export default App;
I'll be honest, "react-browser-router": "^2.1.2", in the package.json file seems like a mistake.
I don't think it's necessary
You are missing react-router-dom as a dependency.
I suggest uninstalling react-browser-router and installing react-router-dom#5 so the Switch and Redirect components can still be imported. Installing the latest RRDv5 is important since there are potential issues with react#18 and the React.StrictMode component and RRDv5 versions below v5.3.3, and if you don't specify v5 then the latest v6 version will be installed which has a lot of breaking changes.
From the terminal in the root project directory run:
npm uninstall --save react-browser-router
npm install --save react-router-dom#5
Update the index.js file to import the BrowserRouter from react-router-dom.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';
import "../src/assets/css/index.scss";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
From here you should restart the app locally to ensure all is well and working before deploying the app again.

MERN App: React's Router Issue upon Rendering

Problem Summary
I am working on a MERN app.
So far I have built the backend, and just starting adding routes in the frontend.
After the process of adding routes to the frontend, an issue arose. The issue is that nothing shows up on the screen. In the Console, the following error shows:
Problem Details
Directory Snapshot 👇
The directory where my app is looks like this:
App.js 👇
// import bootstrap
import "bootstrap/dist/css/bootstrap.min.css";
// import Routers
import {BrowserRouter as Router, Route} from "react-router-dom";
import Navbar from "./components/navbar.component";
import ExerciseList from "./components/exercises-list.component";
import EditExercise from "./components/edit-exercise.component";
import CreateExercise from "./components/create-exercise.component";
import CreateUser from "./components/create-user.component";
function App() {
return (
<Router>
<Navbar/>
<br/>
<Route exact path="/" component={ExerciseList}/>
<Route path="/edit/:id" component={EditExercise}/>
<Route path="/create" component={CreateExercise}/>
<Route path="/user" component={CreateUser}/>
</Router>
);
}
export default App;
package.json 👇
{
"name": "exercise-tracker",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
navbar.component.js 👇
import React, {Component} from 'react'
import { Link } from 'react-router-dom';
export default class Navbar extends Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link to="/" className="navbar-brand">Exercise Tracker</Link>
<div className='collapse navbar-collapse'>
<ul className="navbar-nav mr-auto">
<li className="navbar-item"><Link to="/" className="nav-link">Exercises</Link></li>
<li className="navbar-item"><Link to="/create" className="nav-link">Create Exercise Log</Link></li>
<li className="navbar-item"><Link to="/user" className="nav-link">Create User</Link></li>
</ul>
</div>
</nav>
)
}
}
What I have tried
I tried following the steps on the console and wrapping in a in App.js (I also update App.js's line import {BrowserRouter as Router, Route} from "react-router-dom" to import {BrowserRouter as Router, Route, Routes} from "react-router-dom").
This solves the problem of the white page and the console errors. However, I do not see anything in the body (which is what I expect upon clicking the links in the navbar) and I see the following errors in the console:
At this point I did not know where to go.
In react-router-dom#6 the Route components can only be rendered by the Routes component or other Route components. The Route component API also changed significantly from v6, they render their content on a single element prop taking a ReactNode, a.k.a. JSX, value.
Wrap the Route components in a Routes component.
Render the routed components on the Route components' element prop as JSX
Example:
// import Routers
import {BrowserRouter as Router, Routes, Route} from "react-router-dom";
import Navbar from "./components/navbar.component";
import ExerciseList from "./components/exercises-list.component";
import EditExercise from "./components/edit-exercise.component";
import CreateExercise from "./components/create-exercise.component";
import CreateUser from "./components/create-user.component";
function App() {
return (
<Router>
<Navbar/>
<br/>
<Routes>
<Route path="/" element={<ExerciseList />} />
<Route path="/edit/:id" element={<EditExercise />} />
<Route path="/create" element={<CreateExercise />} />
<Route path="/user" element={<CreateUser />} />
</Routes>
</Router>
);
}
See the Migrating from v5 guide for further breaking changes in v6.

Module not found: Error: Can't resolve 'react-dom/client'

I am using react with the following packages:
{
"name": "demo",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.0.1",
"#testing-library/user-event": "^13.5.0",
"h3-js": "^3.7.2",
"leaflet": "^1.7.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-leaflet": "3.0.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
My index.js looks like the following:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
My App.js is like the following:
import React from "react";
import { render } from "react-dom";
import LeafletMap from "./Map";
class App extends React.Component {
state = { resolution: 8, kRing: 0 };
constructor(props) {
super(props);
this.state = { resolution: 8, kRing: 0 };
}
render() {
return (
<div>
<LeafletMap
resolution={this.state.resolution}
kRing={this.state.kRing}
/>
Resolution:
<input
type="number"
min={0}
max={15}
onChange={this.onChangeResolution}
defaultValue={8}
/>
<br />
K Rings:
<input
type="number"
min={0}
max={100}
onChange={this.onChangeKRings}
defaultValue={0}
/>
</div>
);
}
onChangeResolution = (e) => {
this.setState({ resolution: Number.parseInt(e.target.value) });
};
onChangeKRings = (e) => {
this.setState({ kRing: Number.parseInt(e.target.value) });
};
}
export default App;
When I run my app with npm run start I get the following error:
Compiled with problems:X
ERROR in ./src/index.js 5:0-40
Module not found: Error: Can't resolve 'react-dom/client' in '/home/Desktop/Code/demo_app/src'
I reinstalled all packages and its also listed in npm list:
> npm list
demo_app#0.1.0 /home/Desktop/Code/demo_app
├── #testing-library/jest-dom#5.16.4
├── #testing-library/react#13.0.1
├── #testing-library/user-event#13.5.0
├── h3-js#3.7.2
├── leaflet#1.7.1
├── react-dom#17.0.1
├── react-leaflet#3.0.2
├── react-scripts#5.0.1
├── react#17.0.1
└── web-vitals#2.1.4
Any suggestions why I have problems compiling my application?
The final solution that worked for me was simply to change the React 18 index.js file to the following:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
You still have the older versions of "react" and "react-dom" in your dependencies.
To solve it:
delete these two lines:
"react": "^17.0.1",
"react-dom": "^17.0.1",
Replace them with:
"react": "^18.1.0",
"react-dom": "^18.1.0",
delete the "node_modules" folder
do npm install
This should solve your issue and update your app to react18
You might need to downgrade React and react-dom, here is index.js:
React 17 example:
import React from "react";
import { render } from "react-dom";
import "./index.css";
import App from "./App";
const root = document.getElementById("root");
render(<App />, root);
React 18 example:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
In summary, if you are using React 17 (My version was 17.0.2), you index.js will have to be like the following,
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
if You are using React 18, your index.js file should looks like the following
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
I was facing problem, when I downgraded my react 18 project to react 17 project.
i used,
npm install react#17 react-dom#17
For typescript project,
npm install react#17 #types/react#17 react-dom#17 #types/react-dom#17
A simple solution to fix this would be to first update your react version. Change your index.js for React 18.
Open your terminal in your project's root directory and run the following command:
npm install react-dom#latest react#latest
After installed React 18, if you are still facing an error, you will have to change your index.js file to the as mentioned below:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Ok! Firstly this is what I did. I experienced this problem on React ^16.14.0. I removed the 'client' from 'import ReactDOM from "react-dom/client" in my index.js file. I also commented out the
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
that was there and used
ReactDOM.render(
<App />,
document.getElementById("root")
);
instead. Also, commented out
import reportWebVitals from "./reportWebVitals"; and reportWebVitals();
also. After doing this your code should compile successfully.**
I had a similar problem and I solved it by adding
"noImplicitAny": false
on the tsconfig.json
For react version 18.1 (with typescript),
this works for me
import React from "react";
import { createRoot } from "react-dom/client";
import reportWebVitals from "./reportWebVitals";
import App from "./App";
const root = createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
My issue was the types packages not being upgraded as well. I had to update the #type imports for the new react and react-dom packages.
yarn add #types/react #types/react-dom

I can't display Reactstrap components in ReactJs

Hi guys I'm new to Reactjs, I can run <h1>Hello World </h1> in App.js. But when I use <Container></Container> in Reactstrap even though I have done all the imports, I get a blank page in the browser. App.js is not rendered when I use <Container></Container>.I am not getting any errors either.
App.js => rendered
import React, { Component } from 'react';
import { Container, Row } from 'reactstrap';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
}
export default App;
App.js => not rendered
import React, { Component } from 'react';
import { Container, Row } from 'reactstrap';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Container>
<h1>Hello World</h1>
</Container>
</div>
);
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
package.json
{
"name": "test-react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"bootstrap": "^5.1.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "0.9.5",
"reactstrap": "^9.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Hey here it looks like react-scripts is low version.I upgraded it to 4.0.0 and added the following in package.json
,
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
Problem solved, thank you.

My React App never loads in localhost:3000 its just always spinning (Think React-Router-Dom is the issue)

I have been developing a website in React using React-Bootstrap, and it has worked fine up until I installed and configured React-Router-Dom and started implementing routes, links, etc...(I have also installed react-router-bootstrap to work with it)
I am almost certain it is react-router-dom that is the issue as at the beginning, I was having similar issues. When I made a new fresh project, I decided not to install react-router-dom until towards the end of the development.
When I run NPM Start, it appears on my browser with the React favicon and name of the app, but the loading spinner is just constantly loading.
In the Command-Line, the development server compiles successfully, and there are no errors - so I'm finding it hard to work out where the issue is.
All relevant code is below.
App.js
import './App.css';
import Navigation from "./Components/Nav";
import 'bootstrap/dist/css/bootstrap.min.css';
import { Col, Container, Row } from 'react-bootstrap';
import Karousel from './Components/Carousel';
import YtCard from './Components/Cards/YoutubeCard';
import BandcampCard from './Components/Cards/BandcampCard';
import SpotifyCard from './Components/Cards/SpotifyCard';
import Footer from './Components/Footer';
import { FormspreeProvider } from '#formspree/react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import { HashRouter } from 'react-router-dom'
import Contact from './Pages/Contact';
function App({Component, pageProps }) {
return (
<FormspreeProvider project="{music-boostrap}">
<Router>
<div className="app">
<div className="navigation">
<Navigation/>
</div>
<Switch>
<Route exact path="/" component={App}/>
<Route path="/contact" component={Contact}/>
</Switch>
<div className="carousel">
<Container className="carousel-container" fluid>
<Karousel/>
</Container>
</div>
<div className="description">
<Container fluid>
<Row>
<Col className="desc-col">
<YtCard/>
</Col >
<Col className="desc-col">
<BandcampCard/>
</Col>
<Col className="desc-col">
<SpotifyCard/>
</Col>
</Row>
</Container>
</div>
<Footer/>
</div>
</Router>
</FormspreeProvider>
);
}
export default App;
package.json
{
"name": "music-bootstrap",
"version": "0.1.0",
"private": true,
"dependencies": {
"#formspree/react": "^2.2.3",
"#testing-library/jest-dom": "^5.11.9",
"#testing-library/react": "^11.2.5",
"#testing-library/user-event": "^12.7.3",
"bootstrap": "^4.6.0",
"react": "^17.0.1",
"react-bootstrap": "^1.5.0",
"react-dom": "^17.0.1",
"react-router-bootstrap": "^0.25.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
If any files are missing with code you might think is relevant to solving these issues, please let me know!
You're attempting to render App inside App, which results in an endless recursion, you need to use a different component here
<Route exact path="/" component={App}/>

Categories