How do you switch between pages with React-router-dom? - reactjs

I have a Menu, I need that when I click on an item the Menu disappears. I have seen a solution in this platform to create a Pages folder and there to put all the pages, but it does not allow me to do import Menu from '. / Pages', I get an error: cant resolve'. / Pages. I am working with react-router-dom. Link de posible solution: ReactJS How do you switch between pages in React?
Link sandbox: https://codesandbox.io/s/jovial-bartik-jsjj9 line:12

With the way you've structured your code, You'll have to do as you did for the 404 page:
import MainMenu from "./pages/MainMenu";
alternatively you can add an index.js file in the pages folder and export your components out if you want to keep the ./pages style
i.e
index.js
export * from './MainMenu.js'
export * from './404.js'
...etc

In your MainMenu.jsx file, you need to import React => import React from "react";
Then in your index.js file import the files as =>
import MainMenu from "./pages/MainMenu";
import NotFountPage from "./pages/404";
import Clients from "./pages/Clients";
Edit the index.js file and add the following code segment:
<Router>
<Switch>
<Route exact path="/">
<MainMenu/>
</Route>
<Route path="/404">
<NotFountPage />
</Route>
<Route path="/clients">
<Clients />
</Route>
<Redirect to="/404" />
</Switch>
</Router>

If you are just trying to make a item disappear I will show you how.
import Nav from "./nav";
consturctor(props) {
super(props);
this.state ={
showNav: true
}
}
render() {
const show = this.state.showNav; // make a var to hold current state for this value
return(
{show ? <Nav />: null} // if show then show this component else show null
)
then make a function to change that state
dontShowNav = () => {
this.setState({showNav: false}); // set show to false hide component
}
}

Related

React Milti Page Routing

I am trying to make a multi page app with react routing.
I am have some questions as to how I should structure the routing in the react project.
I want to load my component in my app.js file. In my Home component I would like to have the ability to press a button which will take me to the Poems component, I want the code to be clean and structured into components, therefore I dont want to do all this in the app.js file.
If someone would explain to me how to best do this I can from there be able to route around to multiple pages afterwards depending on the page you are on. I dont want to have a global menu currently (I will want that in the Poems component later though).
Here is my current App.js file & Home.jsx component code just for a more easily adjustable experience for you guys!
Currently it is not optimized to work so if anyone knows a good routing solution for my issue, please give me an example of the routing fix.
Thanks alot
/Jacob
import React from 'react'
import { Route, BrowserRouter as Router, Routes } from 'react-router-dom'
import './App.scss'
import { Home, Poems, Favourites } from './Pages'
const App = () => {
return (
<Router>
<div className="app">
<Home />
<Routes> {/* I read that the Switch was replaces with Routes */}
<Route path="/" exact component={ Home } />
<Route path="/Poems" component={ Poems } />
<Route path="/Favourites" component={ Favourites } />
</Routes>
</div>
</Router>
)
}
export default App
import React from 'react'
import { Route, BrowserRouter as Router, Routes, Link } from 'react-router-dom'
import { Poems } from './Pages'
import './Home.scss'
const Home = () => {
return (
<Router>
<div>
<h1>Petry For All</h1>
<Routes>
<Route path="/Poems" component={ Poems } />
<Link to="/Poems">Poems</Link>
</Routes>
</div>
</Router>
)
}
export default Home
You don't need to (and actually shouldn't) duplicate the <Router> component in all of the route pages. It is only the root component that is acting as a router. So you can keep the App component the same, and then replace the Home component with the following:
import React from 'react'
import { Poems } from './Pages'
import './Home.scss'
const Home = () => {
return (
<div>
<h1>Petry For All</h1>
<Link to="/Poems">Poems</Link>
</div>
)
}
export default Home
The <Link> component resolves into an anchor element which, when clicked, navigates the user to the route passed into the to property.

Basic React Route with dynamic ID not rendering component

I'm trying to figure out why the component SubPage is not rendering whenever the route path of /sub/:_id is visited (e.g. /sub/5f1c54257ceb10816a13d999). This is the first time I've worked with react routes. The :_id part should presumably accept query parameters from the URL dynamically so I cannot see why this is not working.
I can get the /subs page to fetch the API and render each sub on the page but just not each individual sub page.
The route is as follows near the bottom of App.js: <Route path={"/sub/:_id"} component={SubPage} />
Thanks for any help here. I've made a stackblitz for convenience, or you can see the relevant code below:
And subPage.js:
import React from 'react'
export class SubPage extends React.Component {
render() {
return (
<div className="sub-details-individual">
<h1 class="std-intro">Viewing a Single Subscriber</h1>
<div className="sub-specs">
<div className="sub-specs-inner">
id: {this.props.params._id}
</div>
</div>
</div>
)
}
}
And App.js:
import React, {Component} from "react";
import {navLinks} from "./components/nav-links";
import Root from "./components/Root";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import {SubPage} from "./components/subPage";
import ShowSubs from "./components/show-subs";
export default class App extends Component {
constructor() {
super();
this.state = {
navLinks: navLinks,
intro: "hello world",
url: "someurl"
}
}
updateURL = (newUrl) => {
this.setState({
url: newUrl
})
}
render() {
return (
<Router>
<Root navLinks={this.state.navLinks} intro={this.state.intro}></Root>
<Switch>
<Route path="/subs">
<p>subs page</p>
{/*this.updateURL('/subs') fails presumably because it causes the rerender infinitely - but how to solve?*/}
<ShowSubs />
</Route>
<Route path="/">
<p>homepage</p>
</Route>
<Route path={"/sub/:_id"} component={SubPage} />
</Switch>
<p>the url: {this.state.url}</p>
</Router>
);
}
}
Two things:
this.props.params._id will crash since you are missing match before params
this.props.match.params._id
few exact props are missing, especially in the subs path:
<Route exact path="/subs">
Note: the exact prop will be useful in the / route as well.

How to get the React router path on route change

I have this App.jsx that routes to (renders) different components.
But I have set <NavigationBar /> and an h1 tag between Router and Switch because I need to render those two components for every page.
So now what I want is to get the current route name/path name that displays on the browser address bar. This path is changing when I click on different links (Link) to render different components.
But the path value is the same / even though the path is changing for every Link click.
I even used componentDidUpdate but it didn't work as it gave the error
maximum update depth exceeded componentdidupdate
this is my App.jsx
import React, { Component } from "react";
import "./App.css";
import "./css/custom.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import NavigationBar from "./pages/homepage-components/1-navbar";
import HomePage from "./pages/HomePage";
import Post from "./pages/Post";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentPath: "",
};
}
componentDidMount() {
this.setState({
currentPath: window.location.pathname,
});
}
render() {
return (
<Router>
{/* --------------- Navigation Bar --------------- */}
<NavigationBar />
<h1>Path is: {this.state.currentPath}</h1>
{/* --------------- End of Navigation Bar --------------- */}
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/post" component={Post} />
</Switch>
</Router>
);
}
}
export default App;
Even though the different components are rendered as path changes, the value for this.state.currentPath doesn't update.
Can someone help, please?
useLocation hook provides current location:
function NavigationHeader() {
const location = useLocation();
return <h1>Path is: {location.pathname}</h1>;
}

Modal will not display, but the app is not displaying any errors

I am currently learning React and I am trying to create a simple modal that will display when the page loads. When I saved the changes, the page went to white and there aren't any errors in the console. I set the state to true and then tried calling it up in the render, thinking that this could be a way to do it. Can someone tell me what is it that I am doing wrong?
Modal.js
import React from 'react';
class Modal extends React.Component{
constructor(props){
super(props)
this.state = {open:true}
}
render(){
return (
<div open={this.state.open}>
<p>Hello</p>
</div>
)
}
}
export default Modal;
How I imported it into my app.js file
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";
import Modal from './components/Modal';
function App() {
return (
<main>
<Modal />
<Switch>
<Route path="/DadJokes" component={DadJokesApi} />
<Route path="/SportsJokes" component={SportsJokesApi} />
<Route path="/ProgrammingJokes" component={ProgrammingJokesApi} />
<Route path="/" component={HomePage} />
</Switch>
</main>
);
}
export default App;
Try to fix few issues in your code:
you are missing wrap your Routes with Router
the div has open prop which is not required
I have taken your code and made it work basic way. Go thru it and leave a comment for further doubts and I will edit my answer.
https://codesandbox.io/s/fragrant-frost-1hj6r?file=/src/App.js
Also, in your case, try to to maintain a state called open in your parent (eg: App.js) and pass it to your Modal component. In your app.js you can decide and turn the state open to off/on based on your loading condition.

The url is changing but the component is not rendered correctly?

I am having a problem, I am using react router and I will explain the situation.
I have a form to log in, with /authenticate in the url, if authentication is successed then I go to "/" ( home page ) which is doing good now, and I have two navigation bars, one on the left, the other on the top, now when I click on the links, the url changes but the components are not rendered on clicking them, but if I tap the url on the browser and click enter ( page refreshed ) the component is rendered correctly.
Here is my code :
This is the component rendered after the succesful log in, it is my main application, so The MenuGauche and MenuTop are always rendered :
import React, { Fragment } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import MenuGauche from "./MenuGauche";
import MenuTop from "./MenuTop";
import Acceuil from "./Acceuil";
import Roles from "./Roles";
const Application = () => {
return (
<Fragment>
<MenuGauche></MenuGauche>
<MenuTop></MenuTop>
<BrowserRouter>
<Switch>
<Route path="/" component={Acceuil}></Route>
<Route path="/roles" component={Roles}></Route>
</Switch>
</BrowserRouter>
</Fragment>
);
};
export default Application;
And here is my top route component ( the default component suggested by react ) :
function App(props) {
return (
<ThemeProvider theme={theme}>
<I18nProvider locale={props.language.language}>
<BrowserRouter>
<Switch>
<Route exact path="/" component={Application}></Route>
<Route path="/authenticate" component={Authentification}></Route>
</Switch>
</BrowserRouter>
</I18nProvider>
</ThemeProvider>
);
}
Why is that not working ? I would like to get any help to solve that, a solution or a proposition!
One solution is provided, it is that have to keep the BrowserRouter only in the top root component, but still nothing!
here is the modification :
import React, { Fragment } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import MenuGauche from "./MenuGauche";
import MenuTop from "./MenuTop";
import Acceuil from "./Acceuil";
import Roles from "./Roles";
const Application = () => {
return (
<Fragment>
<MenuGauche></MenuGauche>
<MenuTop></MenuTop>
<Route path="/" component={Acceuil}></Route>
<Route path="/roles" component={Roles}></Route>
</Fragment>
);
};
export default Application;
If you feel like I need to provide more code just ask for it.
the problem is that you are using two BrowserRouter component, make sure that is is used once and it is in most top level component in whole application

Resources