I'm trying to redirect to page onclick of a button from my main page App.js, But my redirected page /SelectAirport does not seem to load.
I think there might be something with the link path but I can't figure out how to fix it.
TLDR: The link changes but the content does not load.
App.js
function App() {
return(
<div>
<Button>
<Link to="./SelectAirport">Select Airport</Link>
</Button>
</div>
)
}
export default App;
Full Code here - https://codesandbox.io/s/boring-chihiro-zckfr5?file=/App.js:152-355
Where is your route? You have to first create a route for select-airport or something like that. Currently, you are just trying to load a component directly.
The route might look like this:
import SelectAirport from "./SelectAirport";
<Route path="select-airport" element={<SelectAirport />} />
After this, Link will start to work, and for your case this link should be something like:
<Link to="/select-airport">Select Airport</Link>
So, whenever, it hit select-airport, it will try to find the matching component via route and load that componet.
basic example can be found here. https://v5.reactrouter.com/web/example/basic (v5)
https://reactrouter.com/docs/en/v6/getting-started/overview (v6)
v6 code sample: https://stackblitz.com/github/remix-run/react-router/tree/main/examples/basic?file=src%2FApp.tsx
Use Routes and Route , inside of Route define your component and path for example path='/airports'
import { Button } from "#mui/material";
import React from "react";
import { NavLink } from "react-router-dom";
import SelectAirport from "./SelectAirport";
import {
Routes,
Route,
} from "react-router-dom";
function App() {
return(
<div>
<Button>
<NavLink to="/airports">Select Airport</NavLink>
</Button>
<Routes>
<Route path='/airports' element={<SelectAirport/>} />
</Routes>
</div>
)
}
export default App;
Sandbox example Working example
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.
I've read some answers here and it seems they are all replying to a specific problem. Mine more about usage and placement rather than a problem I am facing. I also read the documentation but it does not answer my question.
My question is where to use react-router components?
Do I import (and use) BrowserRouter in index.js or App.js or does it go wherever the navigation bar is?
Do Route, Switch, NavLink, Link must be in the same module/file? If not, do I use them around the navigation bar element?
On the official website it shows that <Switch> is INCLUDED within <BrowserRouter> tags AFTER <Link> elements were used. Can I conclude from that <Switch> always come in the same element where <Link> elements were used?
I am beyond confused as to where these tags should be used in relation to other tags - not how to get them to work.
Finally, if I have a react app where index.js renders App.js. App.js is like a table of content of the main components I am rendering. Let's say: Header, Main, Footer. Inside the Header there are Greeting and then a NavigationBar. I want my links to be in the NavigationBar component as menu items. Where do I implement react-router components?
Thank you very much in advance.
1 . You can import and use BrowserRouter either in the root of the project which is index.js or in app.js just make sure it wraps around the Switch and Routes .
2 . The Switch Component must wrap all the Route components so this format is the most common way of using it :
<Switch>
<Route exact component={<Component />} path="/" />
</Switch>
You can use NavLink or Link almost anywhere in your components which are imported in Route component prop .
NavLink and Link is just for navigating between Routes in your app .
And for the last part you can have a Layout.js component to have Header Main and Footer components inside of it wrap all the other components which are used in Routes for example :
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
// Router
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
,
document.getElementById('root')
);
App.js
import React from "react";
// Router
import { Switch, Route, withRouter } from "react-router-dom";
// Components
import Home from "./routes/Home/Home";
function App() {
return (
<Switch>
<Route exact component={Home} path="/" />
</Switch>
);
}
export default App;
Home.js
import React from "react";
// Router
import { NavLink } from "react-router-dom";
// Components
import Layout from "../../components/Layout/Layout";
function Home(props) {
return (
<Layout title="Homepage">
<NavLink to="/ss">ss</NavLink>
<NavLink to="/">/</NavLink>
</Layout>
);
}
export default Home;
Define Header Footer and Main in Layout.js :
Layout.js
import React, { Fragment } from "react";
import { Helmet } from "react-helmet";
// Components
import Header from "../Header/Header";
import Footer from "../Footer/Footer";
function Layout({ title, children }) {
return (
<Fragment>
<Helmet>
<title>
{title}
</title>
</Helmet>
<Header />
{children}
<Footer />
</Fragment>
);
}
export default Layout;
The children prop is basically the Home.js component which has Layout wrapper so the Home.js component will display Header Footer from layout and it's own content .
This is the most common way of using the react-router-dom in a react project .
Note
The Switch component will only render the first route that matches/includes the path. Once it finds the first route that matches the path, it will not look for any other matches. Not only that, it allows for nested routes to work properly, which is something that Router will not be able to handle.
Fragment is just for wrapping the component tags like this :
import React , { Fragment } from 'react';
function Component() {
return (
<Fragment>
<Other />
<Main />
</Fragment>
);
}
If you delete Fragment it will throw an error you can read more about Fragments here .
New to react and working with React Router so that I have many pages.
I am in my Home.jsx and it looks like this.
import React, { Component } from 'react';
import randomimage from '../imagefolder/rentalbackground.jpg';
import Header from './Header';
import Footer from './Footer';
import Rentals from './Rentals';
import {
BrowserRouter as Router,
Route,
Redirect,
Link
} from 'react-router-dom';
class Home extends Component {
render() {
return (
<div>
<Header />
<Router>
<div>
<Link to="/rentals">Rentals</Link>
<main>
<Route path="/" component={Rentals} />
</main>
</div>
</Router>
<p>some paragraph here</p>
<img src={randomimage} alt="imagerand" />
<Footer />
</div>
);
}
}
export default Home;
And my Rentals component looks like this.
import React, { Component } from 'react';
class Rentals extends Component {
render() {
return (
<div>
<p>this is for all the rentals</p>
</div>
)
}
}
export default Rentals;
What I am trying to do is create a page called localhost:3000/rentals which only displays the paragraph from the "Rentals" component in a new page. But when I click on the rentals link, which is on the Home.jsx, it displays all the components from the "Home" component including the picture, and the Header and the Footer components too.
I tried using exact path on the Route and nothing happens. How might I achieve this?
This is because you have placed your Router component inside your Home component which in turn have your Header and Footer. So all child components will be rendered inside your Home component.
Your router component should be on the top level of your App and all other components like Home, Rentals etc should be added as a child to the router.
Just to give you an example, it should be something like this.
//Your app initialisation, Top Level
ReactDOM.render(
<div style={{height: '100%'}}>
//All Your routes can be exported at one place and passed to your router as props. This will also help you maintain routes at one place
<Router history={browserHistory} children={routes}/>
</div>,
document.getElementById('root')
)
Will suggest you to read more about using React router and best practices since this is an architecture problem and quite broad topic to be answered here.
I currently have a button
class Button extends Component{
render(){
return(
<View>
onPress= #I need this to return the second page of my app
<Text style={styles.buttonText}>Next Page</Text>
</View>
)
}
}
What should I do to link this button to the second page of my app? Assuming I have already imported the page.
import SecondPage from './SecondPage'
Below example can fix all your issues :
React Router Navigation
Browser Refresh Issue.
Browser Back Button Issue.
Please make sure you have installed react-router-dom
If not installed. Use this command to install npm i react-router-dom
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Page1 from "./Page1";
import Page2 from "./Page2";
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Page1} />
<Route path="/page2" component={Page2} />
</Switch>
</BrowserRouter>,
rootElement
);
Page1.js
import React from "react";
import {Link } from "react-router-dom";
function Page1() {
return (
<div>
<p>
This is the first page.
<br />
Click on the button below.
</p>
<Link to="/page2"><button>
Go to Page 2
</button>
</Link>
</div>
);
}
export default Page1;
Page2.js
import React from "react";
function Page2() {
return (
<div>
<p>This is the second page.</p>
</div>
);
}
export default Page2;
use <Link> from react-router
<Link to ='/href' ></Link>
There are 2 ways you can achieve this. Details below
Option 1: If you are using react router, you could use Link to redirect users to the second page.
Declare a route in your router config to go to the second page and use . More details here
http://knowbody.github.io/react-router-docs/api/Link.html
Option 2: If you are not using react router and just redirecting, use the onClick on the button to redirect to a new URL. E.g. React: How to navigate via clickHandlers?
Note- Option 2 is a dirty way of navigating from one page to other. A sophisticated way will be to use react-router. You will need it when your app grows big and there are many redirects happening on the page.
Hope that helps!
I am working on a sample reactjs application (in learning process). I have a page which list the list of users and a add button to add a new user.
When I click the add button I should navigate to the User Form to create the new user.
After I click the submit button in the user form it should navigate back to the first page where it should list the list of users along with the new user.
How to navigate between pages in react?
You do it with react router. Here is the react router tutorial.
Your list of users is the first page which is shown when you open the site, thus that is your index page and all other pages are routes.
Thus you can do something like this :
You can create a separate file with your routes :
import UserList from 'path/to/user/list';
import AddUserForm from 'path/....';
const routes = (
<Route path="/" component={App}>
<IndexRoute component={UserList}/>
<Route path="addUser" component={AddUserForm}/>
</Route>
);
export default routes;
Then your index.js should look something like this :
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, browserHistory} from 'react-router';
import routes from 'path/to/routes';
ReactDOM.render(<Router history={browserHistory} routes={routes}/>, document.getElementById('root'));
Here you wrap it under Router which comes from react-router, and there you pass history prop which you want to use and routes prop. You can use browserHistory and hashHistory. BrowserHistory shows cleaner urls. With hash history you have something like someurl.com/#/something
Now in your app you can do next :
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
{this.props.children} renders all routes from routes file, because you have specified App component for the main route.
On the add user button onClick event you can navigate to the add user form with browserHistory, thus :
import { browserHistory } from 'react-router;
.........
onClick(){
browserHistory.push("/addUser");
}
.......
render(){
return (
//Userlist with the button
<button onClick={this.onClick.bind(this)}>Add New user</button>
);
}
And then on button click on add user form, the same process, you only need to navigate to the index route with "/", thus :
import { browserHistory } from 'react-router;
.........
onClick(){
//Your code to add user to the list of users
browserHistory.push("/");
}
.......
render(){
return (
//Add user form
<button onClick={this.onClick.bind(this)}>Add User</button>
);
}
Hope this helps.
Apart from browserHistory, you can use hashHistory also by importing it from react-router.
import {hashHistory} from 'react-router';
hashHistory.push('/addUser')