How to setup Routes using React Router in my ReactJS app? - javascript

I have some problem with react-router. It doesn't go to Edit page when I click on id. The id is in URL, but it doesn't do anything.
const Main = (props) => {
const { pathname } = props.location;
return (
<Fragment>
<div>
<div className="container">
<Header />
{pathname === "/create" ? <Create /> : null}
{pathname === '/edit/:id' ? <Edit /> : null}
{pathname === "/" ? <Home /> : null}
</div>
</div>
</Fragment>
);
};
export default withRouter(Main);
app.js:
require('./components/Index');
import React from 'react'
import ReactDOM from "react-dom"
import Index from "./components/Index";
import { BrowserRouter as Router} from "react-router-dom";
import { ToastContainer } from 'react-toastify';
const App =() =>{
}
if (document.getElementById('app')) {
ReactDOM.render(<Router> <Index /> <ToastContainer /></Router>, document.getElementById('app'));
}
index.js:
import React from "react";
import { Route, Switch } from "react-router-dom";
import Main from "./CRUD/Main";
import Create from "./CRUD/Create";
import Edit from "./CRUD/Edit";
import Home from "./CRUD/Home";
const Index = (props) => {
return (
<Main>
<Switch>
<Route path="/Create" component={Create} />
<Route path='/edit/:id' component={Edit} />
<Route exact path="/" component={Home} />
</Switch>
</Main>
);
};
export default Index;
I think main.js have some problems with pathname.

You don't need to do conditional rendering like you are doing in Main when using react-router. Switch will automatically render the first child <Route> or <Redirect> that will match the location.
Hence, you need to remove Main from your router component i.e. Index so that it looks like as shown below:
const Index = (props) => {
return (
<>
<NavBar /> {/* NavBar is optional, I just added for example */}
<Switch>
<Route path="/create" component={Create} />
<Route path="/edit/:id" component={Edit} />
<Route exact path="/" component={Home} />
</Switch>
</>
);
}
NavBar: (Links; just for example)
function NavBar() {
return (
<ul>
<li>
<Link to="/create">Go to create</Link>
</li>
<li>
<Link to="/edit/123">Go to edit with id = 123</Link>
</li>
<li>
<Link to="/">Go to home</Link>
</li>
</ul>
);
}
Now, when you click on the above links, it will automatically take you to the related component (as declared in routes i.e. Index). (no manually condition checking)
And example, to retrieve the URL param i.e. id in Edit component using useParams hook:
function Edit() {
const { id } = useParams<{ id: string }>(); // Remove <{ id: string }> if not using TypeScript
return <h2>Edit, {id}</h2>;
}

Related

How to prevent page reoading after switching routes

My sidebar uses react-router-dom to switch between page files using routes, however when I switch routes, my page reloads. Is there a way I can switch routes without reloading the page?
SideBar
import React from 'react'
import {SideNav_Data} from "./SideNav_Data"
import Sunrise from './Sunrise.png'
function SideNav() {
return (
<div className = "SideNav">
<img src={Sunrise} className='SideNavImg' alt=''/>
<ul className="SideNavList">
{SideNav_Data.map((val, key) => {
return (
<li key={key}
className = "row"
id={window.location.pathname === val.link ? "active" : ""}
onClick = {() => {
window.location.pathname = val.link;
}}>
<div id='icon'>{val.icon}</div>{" "}<div id='title'>{val.title}</div>
</li>
)
})}
</ul>
</div>
)
}
export default SideNav
Sidebar Data
import React from 'react'
import CottageIcon from '#mui/icons-material/Cottage';
import DirectionsCarFilledIcon from '#mui/icons-material/DirectionsCarFilled';
import PersonIcon from '#mui/icons-material/Person';
import AccountBalanceIcon from '#mui/icons-material/AccountBalance';
import AccountCircleIcon from '#mui/icons-material/AccountCircle';
import ContactSupportIcon from '#mui/icons-material/ContactSupport';
export const SideNav_Data = [
{
title: "Home",
icon: <CottageIcon />,
link: "/"
},
{
title: "Cars",
icon: <DirectionsCarFilledIcon />,
link: "/Cars"
},
{
title: "Representatives",
icon: <PersonIcon />,
link: "/Representatives"
},
{
title: "Loan Estimator",
icon: <AccountBalanceIcon />,
link: "/Loan-Estimator"
},
{
title: "Account",
icon: <AccountCircleIcon />,
link: "/Account"
},
{
title: "Support",
icon: <ContactSupportIcon />,
link: "/Support"
},
]
Home page
import React from 'react'
import SideNav from '../Components/SideNav'
function Home() {
return (<div>
<SideNav />
</div>
)
}
export default Home
App.js
import './App.css';
import { BrowserRouter as Router, Routes, Route} from "react-router-dom"
import Home from './Pages/Home';
import Cars from './Pages/Cars';
import Reps from './Pages/Reps';
import LoanEst from './Pages/LoanEst';
import Account from './Pages/Account';
import Support from './Pages/Support';
function App() {
return (
<Router>
<Routes>
<Route path='/' element={<Home />}/>
<Route path="/Cars" element={<Cars />}/>
<Route path="/Representatives" element={<Reps />}/>
<Route path="/Loan-Estimator" element={<LoanEst />}/>
<Route path="/Account" element={<Account />}/>
<Route path="/Support" element={<Support />}/>
</Routes>
</Router>
)
}
export default App;
I've tried switching the "link: " part of the sidebar data to <Link to={Home /}/> but that resulted in the sidebar completely disappearing.
You should use the Link component instead of changing window.location.pathname:
{SideNav_Data.map((val, key) => {
return (
<Link
key={key}
className = "row"
id={window.location.pathname === val.link ? "active" : ""}
to={val.link}
>
<div id='icon'>{val.icon}</div>{" "}<div id='title'>{val.title}</div>
</Link>
)
})}
Issues
Using window.location.pathname to set the current URL path will necessarily trigger a page reload and remount the entire app. Use one of the link components exported from react-router-dom to issue declarative navigation actions within the app.
The SideNav component disappears because it is only rendered when the Home component is rendered when the path is "/". Use a layout route to render the SideNav component
Solution
I suggest importing and using the NavLink component as it's a special version of the Link component that applies an "active" classname by default. If you need to compute the id attribute for the li element then use the useLocation hook to access the current location.pathname value.
Example:
import { NavLink, useLocation } from 'react-router-dom';
...
function SideNav() {
const { pathname } = useLocation();
return (
<div className="SideNav">
<img src={Sunrise} className='SideNavImg' alt='' />
<ul className="SideNavList">
{SideNav_Data.map((val) => (
<li
key={val.link}
className="row"
id={pathname === val.link ? "active" : ""}
>
<NavLink to={val.link} end>
<div id='icon'>{val.icon}</div>
{" "}
<div id='title'>{val.title}</div>
</NavLink>
</li>
))}
</ul>
</div>
);
}
Render the SideNav as part of a layout route so it's conditionally rendered with the routes you want it to be rendered with.
Example:
import {
BrowserRouter as Router,
Routes,
Route,
Outlet,
} from "react-router-dom"
import Home from './Pages/Home';
import Cars from './Pages/Cars';
import Reps from './Pages/Reps';
import LoanEst from './Pages/LoanEst';
import Account from './Pages/Account';
import Support from './Pages/Support';
import SideNav from './Components/SideNav';
const SideNavLayout = () => (
<>
<SideNav />
<Outlet />
</>
);
function App() {
return (
<Router>
<Routes>
<Route element={<SidNavLayout />}>
<Route path='/' element={<Home />} />
<Route path="/Cars" element={<Cars />} />
<Route path="/Representatives" element={<Reps />} />
<Route path="/Loan-Estimator" element={<LoanEst />} />
<Route path="/Account" element={<Account />} />
<Route path="/Support" element={<Support />} />
</Route>
</Routes>
</Router>
);
}
Home
import React from 'react';
function Home() {
return (
<div>
...
</div>
);
}
export default Home;

Why React does not render component when I redirect to product page

I have an error and can not find any solution in google. The error appears when I want to go to a poduct page and press a button on home page to go to a product page and there I don't have any element rendered, I used React Route to user be able to go to product page and add it to a cart and suppose I did something wrong with providing path but not sure.
VM867:236 Matched leaf route at location "/2" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Here is a code for Item Element:
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
function Item() {
const { id } = useParams();
const [item, setItem] = useState([]);
const [loading, setLoading] = useState(false);
console.log("item", item);
// Fetching Data
useEffect(() => {
const fetchedData = async () => {
setLoading(true);
const response = await fetch(`https://fakestoreapi.com/products/${id}`);
const data = response.json();
setItem(data);
};
fetchedData();
}, []);
return (
<div className="container">
{loading ? (
<>
<h3>Loading.....</h3>
</>
) : (
<div className="container">
<p>{item.title}</p>
</div>
)}
</div>
);
}
export default Item;
And for App.js
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import ItemsComponent from "./Componets/ItemsComponent";
import Navbar from "./Componets/Navbar";
import Home from "./Componets/Home";
import Item from "./Componets/Item";
import About from "./Componets/About";
import AboutLink from "./Componets/AboutLink";
import Contact from "./Componets/Contact";
import Footer from "./Componets/Footer";
import "./App.css";
function App() {
return (
<>
<Router>
<Navbar />
<Routes>
<Route
exact
path="/"
element={
<>
<Home />
<ItemsComponent />
</>
}
/>
<Route exact path="/:id" component={<Item />} />
<Route exact path="/about" element={<About />} />
</Routes>
<AboutLink />
<Footer />
</Router>
</>
);
}
export default App;
It also affected all styling.
Maybe it's because you have
<Route exact path="/:id" component={<Item />} />
instead of
<Route exact path="/:id" element={<Item />} />
?
I think that instead of this
<Route exact path="/:id" component={<Item />} />
you want either of those
<Route exact path="/:id" component={Item} />
<Route exact path="/:id" element={<Item />} />

react router giving sub path for clicking again on link --v6

here I am building a website and I am using react-router-dom
everything seems to work fine when I use the Navbar and Footer components in every page.
So I come up with idea to wrap the component in a wrapper which contains Navbar and Footer.
When I click on Link or maybe NavLink, it seems to work fine but when I click again on same or another link in navbar then it navigates to a sub path under the previous selected path.
like this
on Single Click:
http://localhost:3000/projects
on clicking the same link again:
http://localhost:3000/projects/projects
App.js
import './App.css';
import {BrowserRouter as Router, Route, Outlet, Routes} from 'react-router-dom'
import {CommonScreen, Wrapper, About, Email, Projects} from './Barell'
function App() {
return (
<>
<Router>
<Routes>
<Route index element={<Wrapper children={<CommonScreen/>}/>}/>
<Route path='about' element={<Wrapper children={<About/>}/>}/>
<Route path='projects' element={<Wrapper children={<Projects/>}/>}/>
<Route path='email' element={<Email/>}/>
</Routes>
</Router>
<Outlet/>
</>
);
}
export default App;
Navbar.jsx:
import React from 'react'
import '../../index.css'
import { NavLink } from 'react-router-dom'
const links = [
{
name:"Home",
slug:"/",
},
{
name:"Projects",
slug:"projects",
},
{
name:"About",
slug:"about",
},
{
name:"Contact",
slug:"email",
},
]
export const Navbar = () => {
let activeStyle = {
textDecoration: "underline",
};
return (
<>
<nav>
<div id='brand'>Prema<span>culture</span></div>
<ul id='links'>
{
links.map((current,index) => (
<li>
<NavLink
key={index}
to={current.slug}
style={({ isActive }) =>
isActive ? activeStyle : undefined
}
>
{current.name}
</NavLink>
</li>
))
}
</ul>
</nav>
</>
)
}
Wrapper.jsx:
import React from 'react'
import { Navbar, Footer } from '../Barell'
export const Wrapper = ({children}) => {
return (
<>
<Navbar/>
{children}
<Footer/>
</>
)
}
You are using relative paths (versus absolute), so when already on a route, say "/projects", and then click a link that navigates to "about", the code links relative from "/projects" and results in "/projects/about".
To resolve you can make all the link paths absolute by prefixing a leading "/" character. Absolute paths begin with "/".
Example:
const links = [
{
name:"Home",
slug:"/",
},
{
name:"Projects",
slug:"/projects",
},
{
name:"About",
slug:"/about",
},
{
name:"Contact",
slug:"/email",
},
];
Additionally, to make the code more DRY you might also want to convert the Wrapper component into a layout route. Layout routes render an Outlet component for nested routes to be rendered into instead of a children prop for a single routes content.
Example
import React from 'react';
import { Outlet } from 'react-router-dom';
import { Navbar, Footer } from '../Barell';
export const Layout = () => {
return (
<>
<Navbar/>
<Outlet />
<Footer/>
</>
)
}
...
function App() {
return (
<>
<Router>
<Routes>
<Route element={<Layout />}>
<Route path="/" element={<CommonScreen />} />
<Route path='about' element={<About />} />
<Route path='projects' element={<Projects />} />
</Route>
<Route path='email' element={<Email />} />
</Routes>
</Router>
<Outlet />
</>
);
}

React Js: <Link/> not working after build in gh-pages or netlify

I've built a react front end for my rest api. I've got them both deployed! However my navbar component has tags and do not work after clicking on them once. This happens in both netlify and gh-pages. Has anyone encountered this solution before? I am using HashRouter instead of ReactRouter. Thanks for taking your time with this :)
import React from "react";
import { Link } from "react-router-dom";
export default ({ context }) => {
const authedUser = context.authenticatedUser;
//Nav bar conditionally rendered on if the user is logged in or not
return (
<div>
<div className="header-div">
<div>
<Link to="/" className="header-div-left">
Student Courses
</Link>
</div>
<nav>
{authedUser ? (
<React.Fragment>
<div className="header-div-right">
<span className="header-div-right">
Welcome {authedUser.firstName} {authedUser.lastName}
</span>
<Link className="header-div-right" to="/signout">
Sign Out
</Link>
</div>
</React.Fragment>
) : (
<React.Fragment>
<div className="header-div-right-up-in">
<Link className="header-div-right" to="/signup">
Sign Up
</Link>
<Link className="header-div-right" to="/signin">
Sign In
</Link>
</div>
</React.Fragment>
)}
</nav>
</div>
</div>
);
};
import React from 'react';
import {
HashRouter as Router,
Route,
Switch
} from 'react-router-dom';
import './App.css';
import CourseDetail from './components/CourseDetail';
import Courses from './components/Courses';
import CreateCourse from './components/CreateCourse';
import Header from './components/Header';
import UpdateCourse from './components/UpdateCourse';
import UserSignIn from './components/UserSignIn';
import UserSignOut from './components/UserSignOut';
import UserSignUp from './components/UserSignUp';
import NotFound from './components/NotFound';
import PrivateRoute from './PrivateRoute';
import withContext from './Context';
//Connecting the SignUp & SignIn to context.
//This shares the data and actions throughout the component tree
/* Adding the const's as the component to the route handler
lets the components UserSignIn & UserSignUp gain access to
the function in context and any data or actions passed into
<Context.Provider value={value}> */
const UserSignInWithContext = withContext(UserSignIn);
const UserSignUpWithContext = withContext(UserSignUp);
const UserSignOutWithContext = withContext(UserSignOut);
/* To let the user know they are signed in
need to make changes to the name display in the end header */
const HeaderWithContext = withContext(Header);
const CoursesWithContext = withContext(Courses);
const CourseDetailsWithContext = withContext(CourseDetail);
const UpdateCourseWithContext = withContext(UpdateCourse)
const CreateCourseWithContext = withContext(CreateCourse)
export default () => (
<Router>
<div >
<HeaderWithContext/>
<Switch>
<Route exact path="/" component={CoursesWithContext} />
<PrivateRoute path="/courses/create" component={CreateCourseWithContext} />
<Route exact path="/courses/:id" component={CourseDetailsWithContext} />
<PrivateRoute path="/courses/:id/update" component={UpdateCourseWithContext} />
<Route path="/signin" component={UserSignInWithContext} />
<Route path="/signup" component={UserSignUpWithContext} />
<Route path="/signout" component={UserSignOutWithContext} />
<Route component={NotFound} />
</Switch >
</div >
</Router>
);

Component is not Getting Rendered - Dynamic Routing React

I can get the data of the players when i Route to the Players Component,
but when i click on the Link Tags, the PLayersContainer Component is not opening.
This is my App.js File.
import React, { Component } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import Players from './Components/Players'
import PlayersContainer from './Components/Container/playersContainer'
import Navigation from './Components/Navigation';
export default class App extends Component {
state = {
players:[
{
id:1,
name:'Ronaldo'
},
{
id:2,
name:'Messi'
}
]
}
render() {
return (
<Router>
<Navigation />
<Switch>
<Route path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route exact path="/players/:id" render={PlayersContainer} />
</Switch>
</Router>
)
}
}
This is my Players Component.
import React from 'react'
import { Link } from 'react-router-dom'
export default function Players(props) {
const renderPlayers = () => {
let players = props.players.map(playerObj => <li> <Link to={`/players/${playerObj.id}`}> Player {playerObj.name} </Link></li>)
return players
}
return (
<div>
<ul>
{renderPlayers()}
</ul>
</div>
)
}
This is my PlayersContainer Component, where i want to render the individual data of the Player.
import React from 'react'
import { Link } from 'react-router-dom'
export default function PlayersContainer(props) {
const renderPlayers = () => {
console.log(props);
}
return (
<div>
<ul>
{renderPlayers()}
</ul>
</div>
)
}
You have the wrong Route marked as exact. The way its written currently, anything beginning with /players will match the first route. Since its in a switch, only the first match will be rendered.
Change it from:
<Route path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route exact path="/players/:id" render={PlayersContainer} />
to this:
<Route exact path="/players" render={(props) => <Players {...props} players={this.state.players} />} />
<Route path="/players/:id" render={PlayersContainer} />
Now only exactly /players will match the first route, and /players/id can continue past it to match the second.

Categories

Resources