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.
Related
import { useState } from 'react';
import About from './Container/About';
import Profile from './Container/Profile';
import {BrowserRouter as Router,Route} from 'react-router-dom'
function App() {
const [state,setState] = useState('Data')
return (
<div >
<button onClick={()=>setState('About')} >About</button>
<button onClick={()=>setState('Profile')}>Profile</button>
{state}
<Router>
<Route element={<About/>} path='/about' />
</Router>
</div>
);
}
export default App;
Why is the browser router is not working as it is showing nothing in the output?
Why is the browser router is not working as it is showing nothing in the output?Why is the browser router is not working as it is showing nothing in the output?Why is the browser router is not working as it is showing nothing in the output?
You need to update the navigation path in order to make this work. Currently you are only updating your state, which is completely decoupled from React Router.
You can either add a link component or naviagate programmatically.
The following should work in your case
import { useNavigate } from "react-router-dom";
[...]
let navigate = useNavigate();
[...]
<button onClick={()=>{ setState('About'); navigate('/about'); } } >About</button>
Or if you don't need the state for anything other than the navigation, you can remove it and replace your buttons with React Router Link components.
The router component maintains it's own state and routing context. You need to either use a Link component or the navigate function to issue an imperative navigation action. Don't forget that all the Route components need to be wrapped by the Routes component so route path matching and rendering functions.
Example:
import About from './Container/About';
import Profile from './Container/Profile';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
function App() {
return (
<div >
<Router>
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
<Link to='/profile>Profile</Link>
<Routes>
<Route element={<h1>Home</h1>} path='/' />
<Route element={<About />} path='/about' />
<Route element={<Profile />} path='/profile' />
</Routes>
</Router>
</div>
);
}
export default App;
If you decide to use the useNavigate hook to access the navigate function in this App component then the Router will need to be higher in the ReactTree in order for the useNavigate hook and routing components in App to be able to access the routing context.
import React, { Component } from 'react'
import WebFooter from './WebFooter'
import Navbar from './Navbar'
import FrontImage from './FrontImage'
import './App.css'
import OurServices from './OurServices'
import ContactUs from './ContactUs'
import OurTeam from './OurTeam'
export default class App extends Component {
render() {
return (
<div class='bgimg'>
<Navbar/>
<FrontImage/>
<OurServices/>
<OurTeam />
<ContactUs/>
<WebFooter/>
</div>
)
}
}
This is my app.js file.
In navbar component I have login,register and home button.
When I clicked on Login,I the page should navigate to another page which contains navbar and login form
but does not contain other components like our team,contact us
You should use BrowserRouter, Route from react-router-dom.
Finally you App.js will be something like this
return (
<BrowserRouter>
<Navbar />
<Route exact path="/login" component={Login} />
<Route exact path="/services" component={OurServices} />
<WebFooter/>
>
</BrowserRouter>
)
Then in Navbar you should add links to Login in Navbar. An esiest way is to use useHistory hook from react-router-dom. Then push like history.push('/login')
Ask me, if you will have question
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
I am building a consumer facing app with a admin dashboard. I want to keep the routing separate for them and so trying to delegate :-
App.js
import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
//styles
import './style/bootstrap/bootstrap.scss';
//apps
import Mainapp from './mainapp/Mainapp';
import Admin from './admin/Admin';
const MainappContainer = () => (
<Mainapp />
);
const AdminContainer = () => (
<Admin />
);
class App extends Component{
render(){
return (
<Router>
<Switch>
<Route path="/admin" component={AdminContainer}/>
<Route path="/" component={MainappContainer}/>
</Switch>
</Router>
)
}
}
export default App;
Admin.js
import React, {Component} from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
//styles
import './admin-style.scss';
//layout
import ControlPanel from './component/layout/ControlPanel';
import Navbar from './component/layout/Navbar';
//pages
import Quote from './component/pages/quote/Quote';
class Admin extends Component{
render(){
return (
<div className="adminWrapper">
<ControlPanel />
<section className="viewPanel">
<Navbar />
<Router>
<Route path="/quote" component={Quote}/>
</Router>
</section>
</div>
)
}
}
export default Admin;
However when I hit the URL
http://localhost:3000/admin/quote
it doesn't seem to load the quote component
Quote.js
import React, { Component } from 'react';
class Quote extends Component {
render() {
return (
<div className="float-right pr-3">
<h3>
Quote Page
</h3>
</div>
)
}
}
export default Quote;
When dealing with nested subroutes, the easiest solution is to use match.
path - (string) The path pattern used to match. Useful for building nested
Routes.
url - (string) The matched portion of the URL. Useful for building
nested Links.
By design, components placed inside a Route's component render method are given several additional props from react-router-dom. Among them are history and match. You can leverage these props to either to match against sub routes and/or to control browser history location.
In addition, you only need one instance of BrowserRouter sitting at the top-level of the application, then you can use Switch to optionally render any main or sub routes. And you don't need to use class components unless you're utilizing state and/or a class field.
A very basic, rudimentary working example of your application:
src/components/Admin/index.js
import React from "react";
import { Switch, Link, Route } from "react-router-dom";
import ControlPanel from "../ControlPanel";
import Quote from "../Quote";
// since Admin is placed inside a Route's component render
// method, it has access to history and match
function Admin({ history, match }) {
return (
<div className="adminWrapper">
<ControlPanel />
<section className="viewPanel">
<Link to={`${match.url}/quote`}>View quote</Link>
<br />
<Switch>
<Route exact path={`${match.path}/quote`} component={Quote} />
</Switch>
</section>
<br />
<button type="button" onClick={() => history.goBack()}>
Go Back
</button>
</div>
);
}
export default Admin;
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Link, Route, Switch } from "react-router-dom";
import Admin from "./components/Admin";
const linkStyle = {
padding: "0 10px"
};
function App() {
return (
<BrowserRouter>
<Link style={linkStyle} to="/">
Home
</Link>
<Link style={linkStyle} to="/admin">
Admin
</Link>
<Switch>
<Route path="/admin" component={Admin} />
<Route path="/" render={() => <h1>Main App</h1>} />
</Switch>
</BrowserRouter>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
Follow the Nested Routing Example
The main changes you need to do are:
1. Remove the <Router></Router> from Admin component and
2. Prepend match.path to "/quotes", like it is done in Topics component in the example. In the example, Topics is a function component so it is receiving match as function parameter. As your Admin component is class component, you can access it as this.props.match in render method.
<Route path={`${this.props.match.path}/quote`} component={Quote}/>
<Route exact path="/admin" component={AdminContainer}/>
<Route exact path="/admin/quote" component={Quote}/>
This won't route you to /admin/quote instead it will route you to /admin/admin/quote.
Since it is inside admin just /quote is enough
<Route path="/admin" component={AdminContainer}/>
<Route path="/quote" component={Quote}/>
I'm new to JavaScript and React. I seem to be stuck on this question, I have found information but I think that this is not what I'm really looking for perhaps someone can shed some light on the matter.
So what I'm really looking for is a way to create a "mold" page of an node/react app that will display changing information based on the URL a user submits. Say for example look at facebook (or even stackoverflow) one click on a profile of friends 'y' then the url changes to facebook.com/friends-y and if we choose another person it then changes. Thus I believe that's how they must know how to fill their template using the info provided from that URL with names pictures etc.
I saw that a blog suggests to use route another suggest using url queries more so (which I don't know how to read them once given or how to render them say such as with a onChange event sort of thing when say you click on something inside the page).
My question is: Are any of this methods useful, should I combine them I seen websites that uses both or is there another industry standard that i haven't found and perhaps comes with react?
Any guidance would be much appreciated.
First of all i assume that you have multiple component and you want to change from one component to another component via url. so you have to install react router dom
npm install --save react-router-dom
and after then import Router, Route, Link, Switch (whatever you want) from react-router-dom and give route to component inside router tag .... i mention below in my code
import React, { Component } from 'react';
import './App.css';
import Login from './component/login';
import User from './component/user';
import Signup from './component/signup';
import Notfound from './component/notfound';
import { BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";
const Home = () => (
<div>
<h2>Home</h2>
</div>
);
class App extends Component {
constructor(props){
super(props);
this.state={
loggedIn : false
}
}
render() {
return (
<Router>
<div className="App">
<ul className="nav nav-pills">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/login">LogIn</Link>
</li>
<li>
<Link to="/signup">Sign Up</Link>
</li>
<li>
<Link to="/user">User</Link>
</li>
</ul>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/signup" component={Signup} />
<Route path="/user" component={User} onEnter={this.requireAuth}/>
<Route path="*" component={Notfound} />
</Switch>
</div>
</Router>
);
}
}
export default App;
note : in my code i have total 5 component in my project
Login,
User,
Signup,
NotFound,
Home
for more router information you can check in this site. https://reacttraining.com/react-router/web/example/basic
import React , {Component} from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import App from './Components/Home/App'
import Digital from './Components/DigitalStrat/Digital-Strat';
import ServiceLines from './Components/Serviceline/ServiceLines';
import Operations from './Components/OperationTransformation/Operations-
Transformation';
import WhyUs from './Components/WhyUs/Why-us';
import Mission from './Components/Mission/Mission';
import OurGroup from './Components/OurGroup/OurGroup';
import Team from './Components/Team/Team';
import Projects from './Components/Projects/Projects';
import Research from './Components/Research/Research';
import News from './Components/News/News';
import Locations from './Components/Location/Locations';
import registerServiceWorker from './registerServiceWorker';
import NewsDetails from "./Components/NewsDetails/newsDetails";
import i18n from './js/i18n'
import { sliderArrow } from './js/sliderArrow';
import { menu } from './js/menu';
import {withRouter} from 'react-router';
import Coockies from './Components/Cookies/Cookies';
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop);
ReactDOM.render(
<BrowserRouter>
<Switch>
<ScrollToTop>
<Route exact path = "/" component = {App} />
<Route exact path='/index.html' component={App}/>
<Route exact path='/Digital-Strategies.html' component={Digital} />
<Route exact path='/Service-Lines.html' component={ServiceLines} />
<Route exact path='/Operations-Transformation.html' component=
{Operations}/>
<Route exact path='/inside-the-company.html' component={WhyUs}/>
<Route exact path='/Mission.html' component={Mission}/>
<Route exact path='/Our-group.html' component={OurGroup}/>
<Route exact path='/Team.html' component={Team}/>
<Route exact path='/Projects.html' component={Projects}/>
<Route exact path ='/Research-Development.html' component = {Research}/>
<Route exact path='/News.html' component={News}/>
<Route exact path='/news-details.html/:slug' component={NewsDetails}/>
<Route exact path='/Locations.html' component={Locations}/>
<Route exact path='/cookies' component={Coockies} />
</ScrollToTop>
</Switch>
</BrowserRouter>, document.getElementById('root'));
registerServiceWorker();
This is the basic way to route the project. Feel free to ask question.
The way to handle routing in React is with React Router.
With this sort of (virtual) routing there are two main ways that routing needs to be handled.
1. The first is by rendering different components when the url changes—for example rendering a <Home/> component for "/" and an <About/> component for "/about".
An example:
import React, { Component } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import Home from "./pages/Home";
import About from "./pages/About";
class App extends Component {
render() {
return (
<Switch>
<Route exact path="/" component={ Home }/>
<Route path="/about" component={ About }/>
</Switch>
)
}
}
export default withRouter(App);
2. The second case, which I believe your question specifically addresses, is rendering the same component with different data depending on the url—for example having a <Profile/> component but changing its data for "/profiles/1" vs "/profiles/2".
An example:
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
class Profile extends Component {
constructor() {
super();
this.state = {
profileData: {}
}
}
componentDidMount() {
this.fetchData();
}
componentDidUpdate(prevProps) {
const currentId = this.props.match.params.id;
const prevId = prevProps.match.params.id;
if (currentId !== prevId) {
this.fetchData();
}
}
async fetchData() {
const profileId = this.props.match.params.id;
const profileData = await fetch(`http://example.com/api/profiles/${profileId}`);
this.setState({
profileData
});
}
render() {
const { profileData } = this.state;
return (
<div>
<h1>{ profileData.name }</h1>
</div>
)
}
}
export default withRouter(Profile);
Where the containing parent component of <Profile/> has a <Route/> that looks like this:
<Route path="/profiles/:id" component={ Profile }/>
Which is important so that the id is in this.props.match.params.
Note that in the above example the way to check what data to use to populate the view is by checking the :id parameter in the url. Since information about the url is passed to the <Profile/> component as a prop, we can check if the url changes in componentDidUpdate and get new data if there was a change.
Finally, both of these involve a bit of setup with React Router (basically just wrapping your <App/> in a <Router/>) but the documentation should help with that: https://reacttraining.com/react-router/web/guides/quick-start.
Hopefully this helps.