I am trying to build a simple meetup application using React.The folder structure is as below:
Inside AllMeetups.js:
function AllMeetupspage(){
return <div>AllMeetups</div>
}
export default AllMeetupspage;
Inside Favourites.js:
function Favouritespage(){
return <div>favourites</div>
}
export default Favouritespage;
Inside Newmeetup.js,
function NewmeetupPage(){
return <div>Newmeetup</div>
}
export default NewmeetupPage;
Inside App.js,
import { Route } from 'react-router-dom';
import AllMeetupspage from './pages/AllMeetups';
import NewmeetupPage from './pages/Newmeetup';
function App() {
return (
<div>
<Route path='/'>
<AllMeetupspage />
</Route>
<Route path='/new-meetup'>
<NewmeetupPage />
</Route>
</div>
);
}
export default App;
Inside index.js,
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
I want to see the Allmeetups page content when I load browser.But when I load the browser,it displays nothing.I am new to react and javascript.Could anyone please let me know where I go wrong?
If you're using react-router #v6, you need to replace component with element
<Route path="/" element={<AllMeetupspage />} />
...
...
you have to wrap your routes with the BrowserRouter ( in the below image used as Router) from the react-router-dom for the routing to work. I think this is the issue in your code, sorry if am wrong.
Eg:
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
const App = () => {
return (
<>
<Router>
<Switch>
<Route path="/" component={HomePage} />
</Switch>
</Router>
</>
);
};
export default App;
If you are using react-router version#5 or lower you need to do
<Route exact path="/new-meetup" />
because both routes start with the "/" and would always fall back to the first as you don't specify that you want the complete URL match. The exact parameter basically is some kind of regex that says should match the complete url. From the old docs: https://v5.reactrouter.com/web/api/Route/exact-bool
With the version#6 its not necessary anymore as react-router by default will always look for the exact path.
Related
I am running an issue where, regardless of what URL I am putting into my browser, I keep getting routed to my main page. I've posted the code below for you to take a look, but my goal is to have my browser take me to my drivers.jsx component when the URL is localhost:3000/drivers. Currently, when I go to localhost:3000/drivers, it renders my _app.jsx component instead :(. Can someone help me understand why I can never render the Drivers component (in drivers.jsx) when I am at localhost:3000/drivers?
index.jsx:
import { BrowserRouter as Router, Routes, Switch, Route } from 'react-router-dom';
import MyApp from './_app.jsx';
import Drivers from './drivers.jsx'
import React, { Component } from 'react'
import { Link } from "../routes.js"
class Home extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/drivers' element = {<Drivers />}> </Route>
<Route exact path='/' element = {<MyApp />}> </Route>
</Switch>
</Router>
);
}
}
export default Home;
_app.jsx
import React, { Component } from 'react';
import { useLoadScript } from '#react-google-maps/api';
import Map from '../components/map.jsx';
import "../styles/globals.css";
const MyApp = () => {
const libraries = ['places'];
const {isLoaded} = useLoadScript({
googleMapsApiKey: XXXXXXXXXXXXXX,
libraries
});
if (!isLoaded) return <div>Loading...</div>;
return (
<Map />
);
}
export default MyApp;
drivers.jsx
import React, { Component } from 'react';
class Drivers extends Component {
render() {
return (
<div>TEST</div>
);
}
}
export default Drivers;
I've tried putting the routing logic inside _app.jsx instead, but that causes an incredible amount of errors. My thought is index.js should host all the routing logic, but it shouldn't keep rendering MyApp instead of Drivers when the route is "localhost:3000/drivers".
if your react-router-dom version is
6.4.3
then the switch component dosen't work try changing code to this
instead of using Switch. wrap Route inside Routes
<Router>
<Routes>
<Route path='/drivers' element = {<Drivers />}> />
<Route exact path='/' element = {<MyApp />}> />
</Routes>
</Router>
like this
I'm trying to do basic routing in React. Usually what I have done, and what I will mention later on, is use element={<some page>}. But currently I want to learn and experiment what other options there are, so I came across components where you insert a function. I have followed a tutorial and I did the exact same, except the tutorial uses an older version of router dom so it doesn't use Routes.
Here is the code:
App.js:
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
import Register from './pages/register';
import Login from './pages/login';
import PageRender from './PageRender';
function App() {
return (
<Router>
<input type='checkbox' id='theme'/>
<div className="App">
<div className="main">
<Routes>
<Route exact path="/:page" component={PageRender}/>
<Route exact path="/:page/:id" component={PageRender}/>
</Routes>
</div>
</div>
</Router>
);
}
export default App;
PageRender.js:
import React from 'react'
import { useParams } from 'react-router'
import NotFound from './components/NotFound'
const generatePage = (pageName) => {
const component = () => require(`./pages/${pageName}`).default
try {
return React.createElement(component())
} catch (err) {
return <NotFound />
}
}
const PageRender = () => {
const {page, id} = useParams()
let pageName = "";
if(id){
pageName = `${page}/[id]`
}else{
pageName = `${page}`
}
return generatePage(pageName)
}
export default PageRender
The login and register js are just basic arrow functions which display login or register (still didn't come to that part). What I want to do is when I enter the url, let's say for instance: http://localhost:3000/register, it sends me to register page and if I enter a wrong path it will send me to the "NotFound" page. But sadly, it doesn't work. I know I can work around this problem if I simply do this:
<Route exact path="/login" element={<Login/>}/>
This method works, but currently I'm in the process of learning and I'm curious why this method didn't work.
I was able to get your code working in react-router-dom v5, the trick was importing the components once in App so they are built/transpiled. The PageRender component worked as-is.
RRDv5
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import './pages/register';
import "./pages/login";
import PageRender from "./PageRender";
export default function App() {
return (
<Router>
<input type="checkbox" id="theme" />
<div className="App">
<div className="main">
<Switch>
<Route path="/:page/:id" component={PageRender} />
<Route path="/:page" component={PageRender} />
</Switch>
</div>
</div>
</Router>
);
}
RRDv6 - Swap the Switch component to the Routes component, and switch to using the element prop instead of the component prop to render the PageRender component as JSX.
import { BrowserRouter as Router, Routes, Route, Link } from "react-router-dom";
import './pages/register';
import "./pages/login";
import PageRender from "./PageRender";
export default function App() {
return (
<Router>
<input type="checkbox" id="theme" />
<div className="App">
<div className="main">
<Routes>
<Route path="/:page/:id" element={<PageRender />} />
<Route path="/:page" element={<PageRender />} />
</Routes>
</div>
</div>
</Router>
);
}
I want to change header of the page accodring to the url in React.js.
If url is 'localhost:3000/recommendation/loading', I want to show the component 'LoadingMainHeader' at header.
Else if url is not same as above, I want to show the component 'MainHeader' at header.
My code is as below, but it doesn't works. (only MainHeader is shown)
Please let me know how to fix the code. Thanks.
import React from 'react';
import { BrowserRouter, Route, location } from 'react-router-dom';
import Main from './pages/Main';
import Recommendation from './pages/Recommendation';
import Loading from './pages/Loading';
import RandomRecResult from './pages/RandomRecResult';
import SelectedRecResult from './pages/SelectedRecResult';
import MainHeader from './components/common/MainHeader';
import LoadingMainHeader from './components/common/LoadingMainHeader';
function App(location) {
if (location.pathname !== '/recommendation/loading')
return (
<BrowserRouter>
<MainHeader></MainHeader>
<Route exact path="/" component={Main} />
<Route exact path="/recommendation" component={Recommendation}/>
<Route exact path="/recommendation/result_random" component={RandomRecResult}/>
<Route exact path="/recommendation/result_selected" component={SelectedRecResult}/>
</BrowserRouter>
);
else
return (
<BrowserRouter>
<LoadingMainHeader></LoadingMainHeader>
<Route exact path="/recommendation/loading" component={Loading}/>
</BrowserRouter>
);
}
export default App;
check what is getting in location.pathname using the console.
or
try to implement with useLocation hook.
import React from 'react';
import { BrowserRouter, Route, useLocation } from 'react-router-dom';
import Main from './pages/Main';
import Recommendation from './pages/Recommendation';
import Loading from './pages/Loading';
import RandomRecResult from './pages/RandomRecResult';
import SelectedRecResult from './pages/SelectedRecResult';
import MainHeader from './components/common/MainHeader';
import LoadingMainHeader from './components/common/LoadingMainHeader';
function App() {
let location = useLocation()
if (location.pathname !== '/recommendation/loading')
return (
<BrowserRouter>
<MainHeader></MainHeader>
<Route exact path="/" component={Main} />
<Route exact path="/recommendation" component={Recommendation}/>
<Route exact path="/recommendation/result_random" component={RandomRecResult}/>
<Route exact path="/recommendation/result_selected" component={SelectedRecResult}/>
</BrowserRouter>
);
else
return (
<BrowserRouter>
<LoadingMainHeader></LoadingMainHeader>
<Route exact path="/recommendation/loading" component={Loading}/>
</BrowserRouter>
);
}
export default App;
You are doing in a wrong way.
Here is the solution: Codesandbox demo
Note: This is a blueprint how to achieve you goal.
Happy coding :)
I have tried to learn React and now wanted make a Route but it seems like it doesnt render Overview.
Iam thankful for any help.
import Sidebar from "./components/Sidebar";
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Overview from "./pages/Overview";
function App() {
return (
<Router>
<Sidebar />
<Switch>
<Route path="/overview" components={Overview} />
</Switch>
</Router>
);
}
export default App;
import React from 'react';
const Overview = () => {
return (
<>
<div>Please Render!!</div>
</>
)
};
export default Overview;
The Route accepts component as param and not components. See here
Your code should be -
import Sidebar from "./components/Sidebar";
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Overview from "./pages/Overview";
function App() {
return (
<Router>
<Sidebar />
<Switch>
<Route path="/overview" component={Overview} />
</Switch>
</Router>
);
}
export default App;
You have type error, you write components instead of component.
Change this
<Route path="/overview" components={Overview} />
to this
<Route path="/overview" component={Overview} />
Add exact attribute as following:
<Route path="/overview" exact components={Overview} />
You must switch components to component. Just take out the s.
I am using React-Router for the first time. I am trying to get the buttons on the homepage to go to its respective URL, but When I click on a button, the URL changes, but not the view. I don't get any errors on the console, either. I was wondering if somebody can point out what is happening. I wrapped each button with a link, and assigned the path it needs to go to when clicked. I was wondering if anyone can point out what I am doing wrong.
Homepage.js
import React from 'react';
import {Link} from "react-router-dom"
class HomePage extends React.Component {
render(){
return (
<div>
<h1>Welcome</h1>
<p>Please select a category </p>
<Link to="/ProgrammingJokes">
<button>Programming Jokes</button>
</Link>
<Link to="/DadJokes">
<button>Dad Jokes</button>
</Link>
<Link to="/SportsJokes">
<button>Sports Jokes</button>
</Link>
</div>
)
}
}
export default HomePage;
App.js
import React from 'react';
import HomePage from './components/HomePage'
import DadJokesApi from './components/DadJokesApi'
import SportsJokesApi from './components/SportsJokesApi'
import ProgrammingJokesApi from './components/ProgrammingJokesApi';
import { Route, Switch} from "react-router-dom";
function App() {
return (
<main>
<Switch>
<Route path="/" component={HomePage} />
<Route path="/DadJokes" component={DadJokesApi} />
<Route path="/SportsJokes" component={SportsJokesApi} />
<Route path="/ProgrammingJokes" component={ProgrammingJokesApi} />
</Switch>
</main>
);
}
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>,
document.getElementById('root')
);
Try placing your root route at the end of the list.
Since:
A <Switch> looks through its children <Route>s and renders the first
one that matches the current URL.
From https://reacttraining.com/react-router/web/guides/quick-start
<Switch>
<Route path="/DadJokes" component={DadJokesApi} />
<Route path="/SportsJokes" component={SportsJokesApi} />
<Route path="/ProgrammingJokes" component={ProgrammingJokesApi} />
<Route path="/" component={HomePage} />
</Switch>
Your Switch is matching with the first route every time. You need to use
<Route exact path = '/' component = {Component}/>
You can use the exact property on your routes.
When true, will only match if the path matches the location.pathname exactly.
You can read more here https://reacttraining.com/react-router/web/api/Route/exact-bool
The result must be something like this:
<Route path="/DadJokes" exact component={DadJokesApi} />