ReactJS Navigation - reactjs

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')

Related

React Router Link not loading the page

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

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.

How to keep states in components while navigating with hash router inside a single page application

I am building a single page application with React. The app makes a one time request to an API to retrieve a JSON list. The list is displayed in a grid with some informations. The "home" component has a search bar to filter the list. When the user clicks on an element the detail component is presented on full screen. If the user clicks on the back button from the browser, the text from the search bar (home component) is reset. How can I preserve the state in the home component?
This is the App component
import React, {Component} from 'react';
import {Route, HashRouter} from 'react-router-dom';
import './App.css';
import Home from './components/home/Home';
import Detail from './components/detail/Detail';
class App extends Component {
// Route
render() {
return (
<HashRouter>
<div>
<div className="content">
<Route exact path="/" component={Home}/>
<Route path="/detail" component={Detail}/>
</div>
</div>
</HashRouter>
);
}
}
export default App;
This is one of the navigation link from Home component (it is an array of NavLink).
<NavLink className="Member-item" to="/detail"> Detail</NavLink>
This is when I query
This is after I come back from detail component to home component
Any help is really appreciated!

React rendering unnecessary component in my app

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.

Linking button to another page

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!

Resources