How to link different react pages? - javascript

I am new to react,
I want to connect the button on the main page with a separate react page.
Here I want to connect the contact link href directing to the contact react page.
import React from 'react';
(function Nav (){
return(
<div id="navid">
<nav className="navbar fixed-top navbar-expand-lg">
<a className="navbar-brand" href="home">Manav</a>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<a className="nav-link" href="./Contact">Colab</a>
</li>
<li className="nav-item">
<a className="nav-link" href="x">Blogs</a>
</li>
</ul>
</div>
</nav>
</div>
);
}
export default Nav;

Since React apps are usually SPA's (Single Page Application) that means that usually there is just one html page and react will handle the content switching on the page. So using <a> tags will not work since it expects a separate HTML page to exist which does not exist.
The correct way is to use a routing library like react-router and use its Link component to handle the routing or switching the pages.

You have to use react-router-dom npm package to perform routing operations in react.

First you have to install npm install react-router react-router-dom
Now import import { Switch, Route, BrowserRouter } from "react-router-dom" in your App.js file.
Now use <BrowserRouter> <Switch> <Route> tags as shown below:
import Blogs from "./Components/Blogs";
import Colab from "./Components/Colab";
import Nav from "./Pages/Nav";
import { Switch, Route, BrowserRouter } from "react-router-dom";
const App = () => {
return (
<div className="App">
<BrowserRouter>
<Nav />
<Switch>
<Route path="/BLog">
<Blog />
</Route>
<Route path="/Colab">
<Colab />
</Route>
</Switch>
</BrowserRouter>
</div>
);
};
export default App;
after setting up Routes of components in App.js go to your Nav.js
import {Link} from "react-router-dom" in Nav.js and set the Links to the path as shown below:
import React from "react";
import { Link } from "react-router-dom";
const Nav = () => {
return (
<div>
<Link to="Blog" style={linkStyle}>
Blog
</Link>
<Link to="Colab" style={linkStyle}>
Colab
</Link>
</div>
);
};
export default Nav;
Yo dont need to use <a className="nav-link" href="x">Blogs</a> instead we use Link and Route. You can get more information from the documentation of react-Route-dom

Related

How to Navigate to sections with id as well as pages in React Router Dom?

I have a Main page that contains 4 section ** #home, #collection, #products and #contact** and I have 2 different page for /cart and /login
Navbar Code is Here
`<nav>
<div className='wrap-nav'>
<NavLink href="" className='logo'>NILESTORE</NavLink>
<div className='wrap-ul'>
<ul className='nav-links' >
<li><NavLink to="#home">Home</NavLink></li>
<li><NavLink to="#collection">Collection</NavLink></li>
<li><NavLink to="#products">Products</NavLink></li>
<li><NavLink to="#contact">Contact</NavLink></li>
</ul>
<ul className='nav-items'>
<li><NavLink to="/cart" className='cart' data-item={data.cartItems.length}><BsBag /></NavLink></li>
<li><NavLink to="/login" className='login'>Login</NavLink></li>
</ul>
</div>
</div>
</nav>`
App.js code is here
import React from 'react'
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css"
import Navbar from './components/Navbar'
import Cart from './pages/Cart';
import Main from './pages/Main';
function App() {
return (
<>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Main />} />
<Route path="/cart" element={<Cart />} />
</Routes>
</Router>
</>
)
}
export default App
SO when I am in main page that works fine and I can reach that section when clicking the section like when i click on products i can reach on #products
After that when I click on /cart and /login page I can reach on that page but myNavbar is same for all pages so when I click on Products, it doesn't work
I have tried all the possibilities on changing the NavLink like I have changed #products to /#products but also It doesn't work
Is there any solution for that
I think you can do one of these two:
First You can change your navbar and when you go to a page like a login page or cart page , your navbar doesn't show the other option till the user get back to the home page.
Second is that you pass a variable when you click on those (home, collection, products, and contact). you will say okay go to the home page if I am not at the home page then you will check the state and if there was one of these variables (home, collection, products, and contact) you can navigate to them by using js.
pathname: '/somewhere',
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
basically, this is what you find when you use location hook.
for more information check out the website
react-router-dom "#location"
To navigate to a particular section of a particular page, you might want to use a HashLink in your Navbar component.
Installation:
npm i react-router-hash-link
Import it as:
import { HashLink } from 'react-router-hash-link';
And use it as:
<li><HashLink to={"/page#id"}>Contacts</HashLink></li>
You can learn more about the same here
Hope this helps!

React Router Link Element Breaking Page

I have been working on a personal project and recently learned react and packages. I have been looking the past few days at how to fix a problem I have been having with the Link component in React Router but cant find anyone with my problem. Let me begin by saying that I have everything installed correctly and nothing should be conflicting with it, I followed the documentation closely. Essentially when I use <Link> in my code the entirety of the header doesn't display and I get a blank page with no errors. I tried replacing link with <a> and <div> tags and everything shows up fine but just not with the <Link>
Here is the problem code.
import React from "react";
import { Link } from "react-router-dom";
const NavBar = () => {
return (
<header>
<div class="row" id="pageHeader">
<div class="col-0 col-lg-2"></div> {/* spacer for begining of header */}
{/* code for company logo and link back to home page */}
<div class="col-auto">
<Link to="/Home">
<img src="./images/dnf - logo.png" alt="DNF - Logo" /> {/* logo */}
</Link>
</div>
<div class="col">
<h6 class="mt-2">Get It Done Right,<br />The First Time.</h6> {/* Header slogan */}
</div>
</div>
</header>
);
}
export default NavBar;
If anyone knows the issue to this please help I don't know what, if anything, is wrong with my code.
Wrap your Link tag and image with a Router tag.
<Router>
<Link to="/Home">
<img src="./images/dnf - logo.png" alt="DNF - Logo" /> {/* logo */}
</Link>
</Router>
Don't forget to import
import { BrowserRouter as Router, Link } from 'react-router-dom';
In your file where you import router, import BrowserRouter instead of just Router.
import { Link, Route, BrowserRouter as Router, Routes } from "react-router-dom";
Also you have to use the <Link /> inside a <Router> component.
<Router >
<NavBar /> {/* the component which uses <Link /> */}
<Routes>
<Route exact path="/home" element={<Home />} />
</Routes>
</Router>
In my case it worked!
Just try to use the browser developer console to get more idea about the error.

Routes unable to load using react-router

I'm designing a simple application using create-react-app and I've recently delved into the power of react-router. However, I'm having an issue with pages getting stuck trying to load, and I'm not sure why.
I've got a Navbar component, for which I'll condense the gist of what it is.
import React from 'react';
import { BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom';
import BlogPost from '../Pages/BlogPost';
// Condensed because a lot of the detail is unnecessary and no-one likes blocks of unneeded code
class Navbar extends React.Component {
render() {
return (
<Router>
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
</Switch>
</Router>
);
}
}
function About() {
return <h2>The about page.</h2>;
}
export default Navbar;
BlogPost represents a component that is a page in itself. The code looks like this. Again, I'll abstract away from the stuff that's not relevant.
import React from 'react';
import Navbar from '../Components/Navbar';
// Other components on this page. None of them reference the navbar or contain a router of their own.
import BlogBox from '../Sections/BlogBox';
import CommentForm from '../Components/CommentForm';
import CommentBox from '../Sections/CommentBox';
class BlogPost extends React.Component {
getBlogPost(address) {
// Gets blog data (like the title, description, content, image, etc.) using 'fetch' from
// an API at 'address'. Abstracted away because this isn't relevant.
}
componentDidMount() {
console.log("Blog post mounted!");
this.getBlogPost("http://localhost:8080/api/blog/samplepost");
}
render() {
return (
<div className="blog-post">
<Navbar />
<BlogBox post={this.state ? this.state.post : ""}/>
<CommentForm />
<CommentBox comments={this.state ? this.state.comments: ""} />
</div>
);
}
}
export default BlogPost;
The homepage of my application is located at '/'. It's rendered in my index.js file, the code of which is below.
import React from 'react';
import ReactDOM from 'react-dom';
import BlogHome from './Pages/BlogHome';
import BlogPost from './Pages/BlogPost';
ReactDOM.render(
<BlogHome />,
document.getElementById('root')
);
The homepage renders fine, but when I go to navigate to /post, the application attempts to load the page indefinitely, and eventually times out, being unable to do so.
Notice how the BlogPost page component renders the Navbar component, which in turn has a path /post which renders the BlogPost object? I'm not sure if I'm able to change this. Could this be the reason why the /post path can't load?
What concerns me the most here is that I eventually would like to add additional pages which will not only contain this same Navbar, but for which their page links also exist in this Navbar. For example, if I add an About page, this page will not only contain the Navbar, but its link will also be present in this Navbar!
Is there a way I can keep such self-page links in the Navbar, without the recursive render loop occurring?
Issue
You are creating a cycle between rendering Navbar and BlogPost when the current path matches "/post`.
In other words BlogHome renders a Navar which renders a BlogPost which then renders another Navbar and another BlogPost ad nauseam.
Solution
Restructure your navbar and routes a bit to split them out
index.js
Since BlogHome sounds like a page it should be placed on its own route. Move Router here to wrap entire app. Render BlogHome path last as that matches all path prefixes, so it will render if no other route is matched above it by the Switch.
ReactDOM.render(
<Router>
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
<Route path="/" component={BlogHome} />
</Switch>
</Router>,
document.getElementById('root')
);
Navbar
Remove the router and routes, leave links only.
class Navbar extends React.Component {
render() {
return (
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
);
}
}
Now each page should be free to render a Navbar or not.
try to remove Navbar in your BlogPost component, because when the location changes it will switch component here
<Switch>
<Route path='/post' component={BlogPost} />
<Route path='/about'>
<About />
</Route>
</Switch>
and
<nav>
<div id="navigationlinks">
<ul id="navlinks-left">
<li className="nav-item"><Link to='/'>Home</Link></li>
<li className="nav-item"><Link to='/about'>About</Link></li>
</ul>
</div>
</nav>
will persisit.

React-Router not rendering pages

i got a navbar template from bootstrap and tried to configure react-router, the url changes but the pages aren't rendering not sure what if it has to do with my navbar or the router
import React from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import Home from "./pages/home";
import Aboutus from "./pages/Aboutus";
import Services from "./pages/services";
import PrivacyPolicy from "./pages/PrivacyPolicy";
function App() {
return (
<Router>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<Link className="nav-link" to="../pages/home.jsx">
Graphic-Lab
</Link>
</ul>
</nav>
<Switch>
<Route exact path="./pages/home.jsx">
<Home />
</Route>
<Route path="./pages/Aboutus.jsx">
<Aboutus />
</Route>
</Switch>
</Router>
);
}
export default App;
Attribute path of Route expects browser URL to match. Not path of file you want to display.
So it has to be something like this:
<Route path="/something">
<MyCoolComponent/>
</Route>
It renders MyCoolComponent for URL like https://example.com/something.
You can read path definition and see some example at the documentation.
There don't need to use file extensions, because you make an SAP, the file extensions need when you render different HTML pages on different routes, but in React you just imitate the pages with JS. Just use path="/home" and path="/about".

React - Adding a tab to navbar that manipulates page data instead of invoking route redirect

I have a react App and I am using Browser router and a component named Navigation for navigation.
I want to know how to add a tab to the Nav that is not for navigation, but instead allows the user to manipulate a components JSX on a specific page.
I do not know how to structure this. I figure I could use the Context API (maybe?) but before I go down that rabbit hole I figure someone might know a different/better way.
Here is some dummy code
Nav.js
import React from "react";
function Navigation(props){
console.log(props)
return(
<ul>
<li>Landing</li>
<li>Test</li>
<button>Invoke some action on /test</button>
{/* If I am on a page named /test I want this button to have the abillity to trigger a function on that page*/}
</ul>
)
}
export default Navigation
App.js
import React from 'react';
import { BrowserRouter, Route, Redirect } from "react-router-dom";
import Navigation from "./Navigation";
import Test from "./Test";
import { withRouter } from "react-router";
import {Switch} from 'react-router';
import logo from './logo.svg';
import './App.css';
function App(props) {
return (
<div className="App">
<BrowserRouter>
<div>
<Navigation/>
<Switch>
<Route exact path="/test" component={Test} />
<Route exact path="/some-stuff" component={Whatever} />
<Route exact path="/some-more-stuff" component={WhateverElse} />
<Redirect from="/*" to="/test" />
</Switch>
</div>
</BrowserRouter>
</div>
);
}
export default withRouter(App);

Categories

Resources