All I want to do is have a different Navbar for the home page and a different one for the rest of the pages. I have used things like window.location.pathname and also withRouter. These things only work when the page reloads. When using Link and navigate to a new page from Home, the Navbar of the Home page remains on the other pages until I reload and vice versa.
What worked for me is using
useEffect(()=> { document.getElementById("id of home nav").style.display = "none" document.getElementById("id of regular nav").style.display = "block" },[]}
But, I have to do this on every single Component page. I wonder if there is a better way to do this. Thanks for the help.
EDIT:
This is what I have tried now
"/HomeNavbar.jsx"
return (
<>
{window.location.pathname === "/" ? (
"Home Navbar Code Here"
) : null}
</>
);
};
So when I traverse from other pages to the home page this works perfectly. I wrote a similar code in my regular Navbar but am having the same issues again. The navbar only loads once I reload my page.
"/RegularNavbar.jsx"
return (
<>
{window.location.pathname === "/" ? null : (
"Regular Navbar code Here"
)}
</>
);
};
You can create two different layouts (higher order components) with different navbars and wrap the home page with layout1 and other components with layout 2
import React from 'react';
import { Link } from 'react-router-dom';
const Layout1 = (props) => (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<div>{props.children}</div>
</div>
);
export default Layout1;
layout 2:
import React from 'react';
import { Link } from 'react-router-dom';
const Layout2 = (props) => (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topicgdfgdgs</Link></li>
</ul>
<p>this is a different nav bar, different from the home page</p>
<div>{props.children}</div>
<hr/>
</div>
);
export default Layout2;
home component:
import React from 'react';
import Layout1 from '../Layouts/Layout1';
const Home = () => (
<Layout1>
<div>
<h2>Home</h2>
</div>
</Layout1>
);
export default Home;
any other components:
import React from 'react';
import { Link, Route } from 'react-router-dom';
import Layout2 from '../Layouts/Layout2';
const Topics = ({ match }) => (
<Layout2>
<div>
<h3>topics</h3>
</div>
</Layout2>
);
export default Topics;
stackblitz example
Related
i am currently building a shopping website . i finished the homepage and i have to make routing for other pages
i have 3 main files: App.js, Menuitem.js (which is to execute props), and Homepage.js (which also is used to apply executing props from sections array which includes titles and background images and sections paths)
this is the App js
import React from "react";
import Homepage from './Homepage'
import "./styles.css";
import './Homepage.css'
import {Route, Switch} from "react-router-dom";
const Hatspage=function() {
return(
<div>
<h1>
Hats page
</h1>
</div>
)
}
function App() {
return (
<div>
<Switch>
<Route exact path='/'component={Homepage}/>
<Route path='/hats'component={Hatspage}/>
</Switch>
</div>
);
}
export default App
Menuitem.js
import React from 'react'
import {WithRouter} from 'react'
const Menuitem= function(props){
return(
<div className='card' style={{ backgroundImage: `url(${props.imageUrl})` }} >
<div className='text-frame'>
<h1 className='title'>{props.title}</h1>
<p className='subtitle'>shop now</p>
</div>
</div>
)
}
export default Menuitem
Homepage.js
import React from "react";
import sections from './directory-components';
import Menuitem from "./menu-item-components";
const arrayOne=[sections.slice(0,3)]
const arrayTwo=[sections.slice(3,)]
function extract(item){
return(
<Menuitem
title={item.title} imageUrl={item.imageUrl}/>
)
}
function Homepage(){
return(
<div className='directory-menu'>
<div className='content'>
{sections.slice(0,3).map(extract) }
</div>
<div className='second'>
{sections.slice(3,).map(extract) }
</div>
</div>
)
}
export default Homepage
so i need for example when i click on hats picture i switch to hats page . how to do that
image attached
Thanks in advance
reactjs routing
You can do two different approaches. Both of them will require an extra prop that will be the actual url you want to access when clicking the menu item.
Assuming you modify your section array to look like this:
[{title: 'Your title', imageUrl: 'your-image.jpg', linkUrl: '/hats'}]
And you modify your extract function to add the url value as a prop in the MenuItem component:
function extract(item){
return(
<Menuitem
title={item.title} imageUrl={item.imageUrl} linkUrl={item.linkUrl} />
)
}
You can do this
First one: Using a Link component from react router:
import React from "react";
import { Link } from "react-router-dom";
const Menuitem= function(props){
return(
<Link to={props.linkUrl}>
<div className='card' style={{ backgroundImage: `url(${props.imageUrl})`
}} >
<div className='text-frame'>
<h1 className='title'>{props.title}</h1>
<p className='subtitle'>shop now</p>
</div>
</div>
</Link>
)
}
Now you will have to add extra styling because that will add a regular a tag, but I like this approach because for example you can open the link in a new tab since it is a regular link.
Using the history prop.
import React from "react";
import { useHistory } from "react-router-dom";
const Menuitem= function(props){
const history = useHistory()
const goToPage = () => history.push(props.linkUrl)
return(
<div className='card' style={{ backgroundImage: `url(${props.imageUrl})`
}} onClick={goToPage} >
<div className='text-frame'>
<h1 className='title'>{props.title}</h1>
<p className='subtitle'>shop now</p>
</div>
</div>
)
}
This approach is a basic on click so if you press the component it will go to the selected page, this will work but keep in mind that event bubbling will be harder if you add more on clicks inside the menu item, so please be aware of that.
You should fire an event inside your MenuItem in order to redirect the user
import { useHistory } from 'react-router-dom'
const history = useHistory()
<img onClick={() => history.push('/hats')} />
I have a demo here
Its a simple react app using react-router-dom to link to two pages, Home and Info
On the Info page I have two further links.
I would like these links to load components below the links on this page, is this possible with react-router.
Also is it possible to add this link to the url so it would be something like /info/infolinkone
Is this the best way to do this ore does react do it another way.
import React from "react";
import {Link} from 'react-router-dom'
const Info:React.FC = () => {
return (
<div>
<h2>Info</h2>
<ul>
<li><Link>Info Link One</Link></li>
<li><Link>Info Link Two</Link></li>
</ul>
<div>
//Load components here
</div>
</div>
);
};
export default Info;
let me know if this can help you
import React from "react";
import { Link, Route, useRouteMatch } from "react-router-dom";
const Info: React.FC = () => {
let { path, url } = useRouteMatch();
return (
<div>
<h2>Info</h2>
<ul>
<li>
<Link to={`${path}/linkone`}>Info Link One</Link>
</li>
<li>
<Link>Info Link Two</Link>
</li>
</ul>
<div>
<Route exact path={`${path}/linkone`}>
//here you load your component
</Route>
</div>
</div>
);
};
export default Info;
I am working in React.I have created a button ,which on click should lead the user to the newpage.I made a component About and imported it as well.
I created a function routeChange which would direct to a new page on Clicking the button.But when the button is clicked I am not being directed to any page .
Instead I get an error.
Probably there is not any error with folders.
I imported my About Component as:
import React from 'react';
import {Navbar,NavbarBrand, Jumbotron, Button} from 'reactstrap';
import './App.css';
import Description from './Description';
import './description.css';
import {useHistory,withRouter} from "react-router-dom";
import About from './About';
function App() {
const history=useHistory();
routeChange = () =>{
this.history.push('/About');
}
return (
<withRouter>
<Navbar color="dark">
<div className="container">
<NavbarBrand className="navbar-brand abs" href="/">
Cheat Sheet
</NavbarBrand>
</div>
</Navbar>
<Jumbotron>
<p className="lead">Quick Review ,Revision And Mnemonic Are Always Good</p>
<hr my-2/>
<p className="lead">Page is still under Construction</p>
<Button onClick={routeChange} className="About"color="primary">About Us</Button>
</Jumbotron>
<div className="img-thumbnail">
<Description/>
</div>
<div className="footer">
©Abhilekh Gautam all right reserved.
<p>Follow<a rel="noopener noreferrer"href="https://www.quora.com/profile/Abhilekh-Gautam-1" target="_blank">Abhilekh Gautam</a> On quora</p>
</div>
</withRouter>
)
}
export default App;
a couple issues here.
change function App (){} to const App = () => {} its going to help with your binding later because arrow functions are interpreted differently from declarative functions
this function needs some help
routeChange = () =>{
this.history.push('/About');
}
first of all you have to declare the function as a constant because App is a functional component not a class component.
second of all because App is a functional component you don't need the this keyword because routeChange is an arrow function and is bound to App
your final function should look like this:
const routeChange = () => {
history.push('/About');
}
make your button onClick handler an anonymous function so it is called on click only and not on render
<Button onClick={routeChange}/>
this code makes the route change function get called when the button renders. Instead change it to
<Button onClick={() => routeChange()}
make sure /About is a route to another component in your router or else you will get a 404 error or hit your no match component (if you have one)
your final product should look something like this
in app.js
import React from 'react';
import {Navbar,NavbarBrand, Jumbotron, Button} from 'reactstrap';
import './App.css';
import Description from './Description';
import './description.css';
import {useHistory,withRouter, BrowserRouter, Route, Switch} from "react-router-dom";
import About from './About';
function App() {
return (
<>
<Navbar color="dark">
<div className="container">
<NavbarBrand className="navbar-brand abs" href="/">
Cheat Sheet
</NavbarBrand>
</div>
</Navbar>
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/About' component={About}
</Switch>
</BrowserRouter>
</>
)
}
then your home component would look like this:
import {useHistory} from 'react-router-dom'
const Home = () => {
const history = useHistory();
const routeChange = () => {
history.push('/About');
}
return (
<>
<Jumbotron>
<p className="lead">Quick Review ,Revision And Mnemonic Are Always Good</p>
<hr my-2/>
<p className="lead">Page is still under Construction</p>
<Button onClick={() => routeChange()} className="About"color="primary">About Us</Button>
</Jumbotron>
<div className="img-thumbnail">
<Description/>
</div>
<div className="footer">
©Abhilekh Gautam all right reserved.
<p>Follow<a rel="noopener noreferrer"href="https://www.quora.com/profile/Abhilekh-Gautam-1" target="_blank">Abhilekh Gautam</a> On quora</p>
</div>
</>
)
}
export default Home
I have a page with multiple tabs (child). I also change the URL for each tab, but I'm still on the parent page, just changing the URL for the tab.
the problem is that I can't keep the parent page NavLink active when I click on the tab 'cause it changes the URL, but I want to keep that Active on the Tabs URL.
How to do this?
import React from 'react';
import { NavLink } from 'react-router-dom';
export default () => {
return (
<>
<nav className='Navigation'>
<ul className={`Navigation__list ${hide}`}>
<li className='Navigation__list-item'>
<NavLink to="/events" >Events</NavLink>
</li>
</ul>
</nav>
<Tabs />
</>
);
}
// Tabs Component As Child
export default function Tabs () => (
<ul className="events__tab">
<li> <NavLink to="/events"> All Events </NavLink> </li>
<li> <NavLink to="/myevents"> My Events </NavLink> </li>
</ul>
)
Thanks for your Support in Advance!
All you have to do is to Write a condition inside isActive in NavLink, if the current page URL matches with defined URLs, return true otherwise false. use the function inside isActive, if it return true, you'll get active Link..
Example:
isActive={ () => ['/example', '/exampl2'].inclues(currentPageUrl) }
if the current URL matches in the Above Array, your NavLink will be Active as long as URL doesn't match.
for finding the Current Page URL use the useLocation() hook.
import React from 'react';
import { useLocation } from 'react-router-dom';
// Active the Link on two URLs
export default () => {
// extract pathname from location
const { pathname } = useLocation();
return (
<li className='Navigation__list-item'>
<NavLink
to="/events"
isActive={() => ['/events', '/myevents'].includes(pathname)} >
Events
</NavLink>
</li>
);
};
I created a page and show some card also some little details of cards
Now I want to click on any card navigate to this on show all details
How can I get to this page on react js ?
Is this need to Redux ?
I couldn't understand what you said completely, but you can use React-Router to navigate to different pages in Reactjs. To install it using npm, go to your Application directory and enter in command line npm install --save React-Router
Here is a simple code to navigate to different pages:
import React from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const Home=()=>
(<div>
<h2>Home</h2>
</div>
);
const About=()=>
(<div>
<h2>About</h2>
</div>
);
class App extends React.Component {
render() {
return (
<Router>
<div>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<Route exact path="/" component={Home}/>
<Route exact path="/about" component={About}/>
</div>
</Router>
);
}
}
export default App;
I hope it helped...
No need of Redux for your issue.
You just use React-router. you just create two component 1. Cards.js, 2. CardDetails.js and navigate to card details on click event of cards in Card.js
Cards.js
import React from "react";
import { withRouter } from "react-router";
class Cards extends React.Component {
goToCarddetails = (cardId) => {
localStorage.setItem("selectedCard", cardId);
this.props.history.push('/card-details');
// you can manage here to pass the clicked card id to the card details page if needed
}
render() {
return ( <div>
<div onClick = {()=>this.goToCarddetails('cardId1')}> card 1 </div>
<div onClick = {()=>this.goToCarddetails('cardId2')}> card 2 </div>
<div onClick = {()=>this.goToCarddetails('cardId3')}> card 3 </div>
</div>
)
}
}
export default withRouter(Cards);
With above on clicking any card you will be navigated to card details page.
CardDetails.js
import React from "react";
class CardDetails extends React.Component {
render() {
let selectedCardId = localStorage.getItem("selectedCard");
// you can get this cardId anywhere in the component as per your requirement
return ( <div>
card details here
</div>
)
}
}
export default CardDetails;
Note : I'm using react-router 4 here in example.