React Router Issue: React render two components in the same page - javascript

I'm having issues with my project, actually i'm trying to handle a 404 page when the user enters different url outside of the Routes in my App, but using my knowledge of React and react-router only needs to put the last route has no path and exact path wrapped by a Switch from react-router but not work well, the home page is rendering the Home and the NotFound components at same time.
I've tried to remove Container component inside the Router but that makes that all of the components after MenuBar disappears.
I've tried to put path='*' in the last Route having 2 components rendered in the same page.
A picture of what i'm talking about:
2 components at same time
My project have 3 principal files:
1.- Index.js :
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import ApolloProvider from './ApolloProvider';
import 'semantic-ui-css/semantic.min.css';
import 'animate.css/animate.min.css';
import './App.css';
ReactDOM.render(ApolloProvider, document.getElementById('root'));
serviceWorker.unregister();
2.- ApolloProvider.js (using Apollo with GraphQL) :
import React from 'react';
import App from './App';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from '#apollo/react-hooks';
const httpLink = createHttpLink({
uri: 'http://localhost:5000/graphql'
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
export default (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
);
3.- And finally App.js :
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Container } from 'semantic-ui-react';
import MenuBar from './Components/MenuBar';
import Home from './Pages/Home';
import Login from './Pages/Login';
import Register from './Pages/Register';
import NotFound from './Pages/404';
const App = props => (
<Router>
<Switch>
<Container>
<MenuBar />
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Container>
</Switch>
</Router>
);
export default App;
I only need to render Home component when the user visits '/' but it's weird how react-router is rendering two components at same time, please le me know if you find where i'm wrong or a solution for that, i'll being posting updates if i find a solution or whatever.
Thanks in advance mates!.

Thanks to #skyboyer and #Hugo Dozois the issue was fixed, this is the updated App.js for future references:
const App = props => (
<Router>
<Container>
<MenuBar />
<Switch>
<Route exact path='/' component={Home} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={Register} />
<Route path='*' component={NotFound} />
</Switch>
</Container>
</Router>
);
Best Regards!

Related

React-router is not displaying component in the browser

Inside App.js:
import React, { useState } from 'react';
import './App.css';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Dashboard from './components/Dashboard/Dashboard';
import Preferences from './components/Preferences/Preferences';
import Login from './components/Login/Login';
function App() {
const [token, setToken] = useState();
if(!token) {
return <Login setToken={setToken} />
}
return (
<div className="wrapper">
<h1>Application</h1>
<BrowserRouter>
<Routes>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} /></Route>
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} /></Route>
</Routes>
</BrowserRouter>
</div>
);
}
export default App;`
Inside Dashboard.js (../src/components/Dashboard/Dashboard.js):
import React from 'react';
export default function Dashboard() {
return(
<h2>Dashboard</h2>
);
}
Url: http://localhost:3000/dashboard
I want to see the Dashboard content along with the App page content (Application and Dashboard headers) when I load the browser. But when I load the browser, it only displays the App page content and getting the same error:
"Matched leaf route at location "/dashboard" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page."
You are using Routes instead of Router. Replace it on your line 3 and in the return().
Source: React-router https://v5.reactrouter.com/web/api/Route
//...
import { BrowserRouter, Route, Router } from 'react-router-dom';
//...
return ( ...
<Router>
/*<Route path="/dashboard">*/
<Route path="/dashboard" element={<Dashboard/>} />
/*<Route path="/preferences">*/
<Route path="/preferences" element={<Preferences/>} />
</Router>
...)
export default App;
Please specify which version of React router you are using, since a lot of the functionality has changed, is it 6.4 or is still 5 ?
Either way, please remove the comments of the routes, I don't think they help at all.
if you have chosen BrowserRouter from the 6.4 version then it should be used like this
import { BrowserRouter, Route } from 'react-router-dom';
return (
<BrowserRouter>
<Route path="/" element={<RootComp />} >
<Route path="dashboard" element={<Dashboard/>} />
<Route path="preferences" element={<Preferences/>} />
</Route>
</BrowserRouter>
)
export default App;
Where <RootComp /> should have an <Outlet /> as children
import { Outlet } from 'react-router-dom';
const RootComp = () => {
return <div><Outlet /></div>
}
export default RootComp;
Again, this is for the latest React Router component, however, I would advise using createBrowserRouter() rather than the old component-based trees, this way you can programatically create and manage the routes in an Object.

Routing is not working using react-router-dom-v6.4.2 [duplicate]

This question already has an answer here:
React router routers not showing
(1 answer)
Closed 4 months ago.
Intro
I had created a react starter application
Problem
I had created a 3 components in /src/pages named AddCoupon, Addvertical, Addmetadata. Now then I created a file Routes.js in /src.
Routes.js
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import AddCoupon from './pages/addCoupon';
import AddMetadata from './pages/addMetadata';
import AddVertical from './pages/addVertical';
import Login from './pages/login';
const Routes = () => {
return (
<>
<Router>
<Switch>
<Route path="/addcoupon">
<AddCoupon />
</Route>
<Route path="/addmetadata">
<AddMetadata />
</Route>
<Route path='/addvertical'>
<AddVertical />
</Route>
<Route path="/">
<Login />
</Route>
</Switch>
</Router>
</>
)
}
export default Routes
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter as Router } from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router >
<App />
</Router>
</React.StrictMode>
);
reportWebVitals();
What I want?
So basically what I want is that when I type http:localhost:3000/addcoupon, it should render AddCoupon Component and same for other 2 components but right now it's showing nothing.
I dont want to use any navbar. What I want is simply when I hit the endpoints mentioned in Route.js, it should render that component.
Router 6 uses different syntax compared to earlier versions. Please check out the documentation:
https://reactrouter.com/en/v6.3.0/getting-started/overview
For your particular case, you need to remove switch, and pass element to route, and wrap all Route elements in Routes element, like so:
const Routes = () => {
return (
<>
<Routes>
<Route path="/addcoupon" element={<AddCoupon />}/>
<Route path="/addmetadata" element={<AddMetadata />}/>
<Route path='/addvertical' element={<AddVertical />}/>
<Route path="/" element={<Login />}/>
</Routes>
</>
)
}
In order for routes to work, you also need to wrap App element in Router element, like below:
import ReactDOM from 'react-dom'
import { BrowserRouter as Router } from 'react-router-dom'
import App from './App'
import './styles/index.scss'
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
)
Final step, render Routes inside of App element or wherever you want to use it:
const App = () => {
return <Routes/>
}

Login.js is not showing div in my react project

So my div is not showing up on the localhost site from my login.js file. Am I doing something wrong with the routes or something? I don't know why nothing it is not being shown.
login.js file:
import React from 'react';
const Login = () => {
return <div>Login</div>;
};
export default Login;
Here is my app.js file:
import React, { Fragment } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import './App.css';
const App = () => (
<Router>
<Fragment>
<Navbar />
<Routes>
<Route exact path='/' element={<Landing/>} />
</Routes>
<section className="container">
<Routes>
<Route exact path='/Register' element={<Register/>} />
<Route exact path='/Login' element={<Login/>} />
</Routes>
</section>
</Fragment>
</Router>
);
export default App;
Please Help!
It's should work.
I test it and It's working! I don't get any problem.
You can test by do these:
Remove 'exact' from each route. In version of router 6 don't need to write 'exact'.
Write route path in lowercase. // => "/login"
And check your Login component's path properly.
Best of Luck. Happy Coding!

Rendering <Context> directly is not supported and will be removed in a future major release error

i am getting the following errror:
Warning: Rendering directly is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?
This is my app.js component:
import React from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from "./pages/Home";
import SignInSide from "./components/SignInSide";
import AboutUs from "./pages/AboutUs";
import ourservices from "./pages/OurServices";
import portfolio from "./pages/portfolio";
import SignUp from "./components/signup";
import booking from "./pages/book";
import PreviousBookings from "./pages/PreviousBookings";
import BookingContext from "./context/bookings/BookingContext";
function App() {
return (
<>
<BookingContext>
<Router>
<Navbar />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/aboutus" component={AboutUs} />
<Route path="/ourservices" component={ourservices} />
<Route path="/developer" component={portfolio} />
<Route path="/login" component={SignInSide} />
<Route path="/signup" component={SignUp} />
<Route path="/booking" component={booking} />
<Route path="/booking-history" component={PreviousBookings} />
</Switch>
</Router>
</BookingContext>
</>
);
}
export default App;
I am trying to use the useContext hook.
Solution for me was changing:
import AuthProvider from "./context/AuthContext";
To:
import {AuthProvider} from "./context/AuthContext";
I'm new with React, might be because AuthProvider is not the default export
I had this error not too long ago. The issue was with my imports...so I was importing the context itself and rendering that, rather than the context provider function itself
in my opinion, you need a file Context Provider ;
example :
"./BookingProvider"
function BookingProvider()
return (
<BookingContext.Provider>
....
<BookingContext.Provider>
)
export default BookingProvide
"app.js"
<BookingProvide >
....
</BookingProvide>

React Router Not Working Like I Need It Too

Im trying to figure out how to get my navigation bar setup as most of the UI is coming together. I have setup my index.js and also a Route.js and then linked them with my different components like so:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import { Auth0Provider } from "./react-auth0-spa.js";
import { useAuth0 } from "./react-auth0-spa";
import Routes from "./Routes"
import config from "./utils/auth_config.json";
import { BrowserRouter } from "react-router-dom";
// A function that routes the user to the right place
// after login
const onRedirectCallback = appState => {
history.push(
appState && appState.targetUrl
? appState.targetUrl
: window.location.pathname
);
};
ReactDOM.render(
<Auth0Provider
domain={config.domain}
client_id={config.clientId}
redirect_uri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
<BrowserRouter>
<Routes />
</BrowserRouter>
</Auth0Provider>,
document.getElementById("root")
);
Routes.js
import React, { Component } from "react";
import { Router, Route, Switch, BrowserRouter } from "react-router-dom";
import {Link } from "react-router-dom";
import Profile from "./components/user/Profile";
import PrivateRoute from "./components/user/PrivateRoute";
import history from "./utils/history.js";
import HomePage from "./modules/HomePage.js";
import ProductPage from "./modules/ProductPage";
class Routes extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>
)
}
}
export default Routes;
but when i reload my site it just continues to say localhost:8080/ProductPage like its suppose to be the default, then when i manually enter localhost:8080/ and click on a button after linking it with
<Link to="ProductPage">
it will show on the tab localhost:8080/ProductPage but wont actually redirect me to the other component, i am just wondering what i am doing wrong?
Issue
You have your "home" route listed first in the Switch.
Switch
Renders the first child <Route> or <Redirect> that matches the location.
"/" is less specific and matches basically all routes, so even though the URL is "/ProductPage", "/" still matches it and HomePage is rendered.
Solution
Either move it after the other more specific routes or use the exact prop on it.
<Router history={history}>
<Switch>
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
<Route path="/" component={HomePage} />
</Switch>
</Router>
or
<Router history={history}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>

Categories