I am new to ReactJs and I want to navigate to another component on button click. I just want to perform a simple routing. This is the code that I tried. But I am not able to route it.
in App.js
import React from 'react';
import DepartmentShow from './Components/Departments/DepartmentShow';
import {BrowserRouter, Link, Route, Switch} from 'react-router-dom'
<BrowserRouter>
<Link to = '/departments'>Departments</Link>
<Switch>
<Route path='/customers' component= {CustomerList} exact={true} />
<Route path='/customers/new' component= {AddCustomer} />
<Route path='/customers/edit/:id' component= {EditCustomer} />
<Route path='/customers/:id' component= {CustomerShow} />
<Route Path='/departments' component={ListDepartment} exact={true}/>
<Route exact Path='/departments/:id' component={DepartmentShow} />
</Switch>
</BrowserRouter>
ListDepartment.js
<ul>
{
props.department.map((dept)=>{
return <li key={dept._id}><Link to={`/departments/${dept._id}`}>{dept.name}</Link>
<button onClick={()=>{handleRemove(dept._id)}}>remove</button>
<Link to={`/departments/${dept._id}`}><button>Show</button></Link>
</li>
})
}
</ul>
Note: cuustomer component i can route but not department.. :(
DepartmentShow.js
import React from 'react'
function DepartmentShow (props){
return(
<div>
<h1>Show Details</h1>
</div>
)
}
export default DepartmentShow
When i click on show button my show component should show.
when i click on show i get url like http://localhost:3000/departments/5e922d889b38110016837a77
but its is not routing to show component.
Related
Trying to create an about page for a website im working on, I found this solution on Stack but it does not work for me. I was using an outdated tutorial for my original code, this is my current code:
About.js:
import React from "react";
import { Link, Route, useMatch } from "react-router-dom";
import SinglePage from "./SinglePage";
const About = () => {
//const match = useMatch('/');
return (
<div className="about__content">
<ul className="about__list">
<li>
<Link to={'about-app'}>About App</Link>
</li>
<li>
<Link to={'about-author'}>About Author</Link>
</li>
</ul>
<Route path={':slug'}>
<SinglePage />
</Route>
</div>
);
};
export default About;
Index.js where I am rendering the component:
import React from "react";
import ReactDOM from "react-dom";
import TodoContainer from "./functionBased/components/TodoContainer"; // Component file
import "./functionBased/App.css"; // Style sheet
import { HashRouter as Router, Routes, Route } from "react-router-dom"; // Router file
import About from "./functionBased/pages/About";
import NotMatch from "./functionBased/pages/NotMatch";
ReactDOM.render(
<React.StrictMode>
<Router>
<Routes>
<Route exact path="/" element={<TodoContainer />} />
<Route path="/about/*" element={<About />} />
<Route path="*" element={<NotMatch />} />
</Routes>
</Router>
</React.StrictMode>,
document.getElementById("root")
);
Issues
The About component is directly rendering a Route component. The Route component can only be rendered by a Routes component or another Route component as a nested route.
The react-router-dom#6 Route components render their content on the element prop.
Solution
Import the Routes component and wrap the descendent Route component rendered by `About.
Render SinglePage on the route's element prop.
Example:
import React from "react";
import { Link, Routes, Route } from "react-router-dom";
import SinglePage from "./SinglePage";
const About = () => {
return (
<div className="about__content">
<ul className="about__list">
<li>
<Link to="about-app">About App</Link>
</li>
<li>
<Link to="about-author">About Author</Link>
</li>
</ul>
<Routes>
<Route path=":slug" element={<SinglePage />} />
</Routes>
</div>
);
};
export default About;
Alternative
You could alternatively move the SinglePage route out to the main router as a nested route (instead of where it is as a descendent route).
Example:
import React from "react";
import { Link, Outlet } from "react-router-dom";
import SinglePage from "./SinglePage";
const About = () => {
return (
<div className="about__content">
<ul className="about__list">
<li>
<Link to="about-app">About App</Link>
</li>
<li>
<Link to="about-author">About Author</Link>
</li>
</ul>
<Outlet />
</div>
);
};
export default About;
...
<Router>
<Routes>
<Route path="/" element={<TodoContainer />} />
<Route path="/about" element={<About />}>
<Route path=":slug" element={<SinglePage />} />
</Route>
<Route path="*" element={<NotMatch />} />
</Routes>
</Router>
You are defining the routes with /about/* and accessing them with about-something which does not exist at all, add \about\author in to for Link.
Consider the code :
import React from 'react';
import { Link, BrowserRouter } from 'react-router-dom';
import { ReactComponent as Logo } from '../../assets/crown.svg';
import './header.styles.scss';
const Header = () => (
<BrowserRouter>
<div className='header'>
<Link className='logo-container' to='/'>
<Logo className='logo' />
</Link>
<div className='options'>
<Link className='option' to='/shop'>
SHOP
</Link>
<Link className='option' to='/contact'>
CONTACT
</Link>
</div>
</div>
</BrowserRouter>
);
export default Header;
This is a header that I use in my App.
Look like this :
When I click on the crown the URL (in the browser) changes , but the page doesn't change , it stays on the same page.
Same thing happens with the other Links , CONTACT & SHOP.
What's wrong with the <Link> tag ? Why doesn't it forward to the to that's written on the Link tag ?
Did you setup the routes? This would be in AppRouter.js for example:
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path='/' component={Home} exact={true} />
<Route path='/shop' component={Shop} exact={true }/>
<Route path='/contact' component={Contact} exact={true} />
<Route component={ErrorPage} />
</Switch>
</div>
</BrowserRouter>
If you want navigate your user try use NavLink
or add withRouter to component and push them to the other pages
-- NavLink solution :
import { NavLink, BrowserRouter } from 'react-router-dom';
and then in your JSX use this instead
<NavLink className='logo-container' to='/'>
<Logo className='logo' />
</NavLink>
-- push solution:
import { withRouter , BrowserRouter } from 'react-router-dom';
export your component like this
export default withRouter(Header);
then you can use any tags you want and listen at events on them
<p className='logo-container' onClick = {() => props.history.push('/')}>
<Logo className='logo' />
</p>
in order to navigate to different components you have to define routers. So react-router-dom will know what to display.
The other thing is u cannot put BrowserRouter inside the Header component. Component BrowserRouter wraps the history object in the browser and passes it to down to component tree. BrowserRouter is a wrapper. Header should be placed inside the BrowserRouter but not here. just create your Header Component without BrowserRouter.
here is how you should properly implement routing in react.js
in src/omponents folder create your components for routes.
src/component/shop.js:
import React from "react";
const Shop = () => <div>my shop component</div>; //define your component
export default Shop;
create all other components like so including Header but without BrowserRouter. then in src folder create a new directory name routers. inside of it create AppRouter.js
src/routers/AppRouter.js
import { BrowserRouter, Route, Switch } from "react-router-dom";
import React from "react";
import Shop from "../components/Shop";
//import all other routes from components directory.
import Header from "../components/Header"
const AppRouter = () => (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path="/" component={YourHomeComponent} exact={true} />
<Route path="/contact" component={Contact} />
<Route path="/shop" component={Shop} />
<Route component={NotFound} />
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
// When react-router sees “Switch” it is going to move through your route definitions in order and it’s going to stop when it finds a match.
finally in app.js
import React from "react";
import ReactDOM from "react-dom";
import AppRouter from "./routers/AppRouter";
ReactDOM.render(<AppRouter />, document.getElementById("app"));
I'm starting in React and I'm curious about about if have any way to change a page without reload all the html, changing only a content component for example.
I know that there is a way to change the component without change the url but I thought that if the url change too the application would be better.
React Router is the exact thing you're looking for
Here, how you can achieve what you're looking for.
First, wrap your app with BrowserRouter
import { BrowserRouter } from "react-router-dom";
import React from 'react';
class App extends React.Component {
return (){
return (
<BrowserRouter>
<SomeComponent />
</BrowserRouter>
)
}
}
Now just use the Route and Link. Route told the application which component to render on the basis of the current route and Link changes the URL without reloading the whole page
import { Route, Link, Switch } from "react-router-dom";
import React from 'react';
import {Circle, Square} from './someFileWithComponents';
class SomeComponent extends React.Component {
render(){
return (
<div>
<Link to='/circle' >Circle</Link>
<Link to='/square' >Square</Link>
<Switch>
<Route path='/circle' component={Circle} />
<Route path='/square' component={Square} />
</Switch>
</div>
)
}
}
React Router is what you looking for
const AppRouter =()=>(
<BrowserRouter>
<div>
<Header/>//where Header components contains the navigation
<Switch>
<Route path="/" component={BookListPage} exact={true} />
<Route path="/create" component={AddBookItem} />
<Route path="/edit/:id" component={EditBookItem} />
<Route path="/help" component={HelpPage} />
<Route component={NotFoundPage} />
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
Hi guys I am a newbie to reactjs, I am trying to learn reactjs router. I have this weird thing happening to my Dashboard routes.
My App component have two routes "/login" and "/"
'/login' shows up the login screen and the '/' shows up the main dashboard screen.
In the dashboard I have sidenavigation component and Main content component.
I am trying to nest a set of Routes inside main component.
The routes are working fine when i navigate it through the links in the side navigation component. But when I try to click back or forward button in the browser it doesn't work. I am getting a blank screen without anything loaded.
please need your help guys.. any help will be highly appreciated.
Please find the code below.
//App.js
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import MainPage from "./Mainpage";
import LoginPage from "./components/pages/LoginPage";
import "./styleFiles/index.css";
class App extends Component {
render() {
return (
<div className="flexible-content">
<Route path="/" exact component={MainPage} />
<Route path="/login" component={LoginPage} />
</div>
);
}
}
export default App;
//MainPage.js
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import SideNavigation from "./components/sideNavigation";
import Footer from "./components/Footer";
import "./styleFiles/index.css";
import DashboardPage from "./components/pages/DashboardPage";
import ProfilePage from "./components/pages/ProfilePage";
import TablesPage from "./components/pages/TablesPage";
import InventoryPage from "./components/pages/InventoryPage";
class MainPage extends Component {
render() {
return (
<BrowserRouter>
<div className="flexible-content">
<SideNavigation />
<main id="content" className="p-5">
<Switch>
<Route path={"/"} exact component={DashboardPage} />
<Route path={"/Dashboard"} exact component={DashboardPage} />
<Route path="/profile" component={ProfilePage} />
<Route path="/tables" component={TablesPage} />
<Route path="/inventory" component={InventoryPage} />
<Route component={DashboardPage} />
</Switch>
</main>
<Footer />
</div>
</BrowserRouter>
);
}
}
export default MainPage;
//sideNavigation.js
import React from "react";
import logo from "../assets/logo_.svg";
import { MDBListGroup, MDBListGroupItem, MDBIcon } from "mdbreact";
import { NavLink } from "react-router-dom";
import "../styleFiles/sideBar.css";
const sideNavigation = () => {
return (
<div className="sidebar-fixed position-fixed">
<a href="#!" className="logo-wrapper waves-effect">
<img alt="MDB React Logo" className="img-fluid" src={logo} />
</a>
<MDBListGroup className="list-group-flush">
<NavLink exact={true} to="/" activeClassName="activeClass">
<MDBListGroupItem className="bgc">
<MDBIcon icon="chart-pie" className="mr-3" />
Testing Dashboard
</MDBListGroupItem>
</NavLink>
<NavLink to="/profile" activeClassName="activeClass">
<MDBListGroupItem className="bgc">
<MDBIcon icon="user" className="mr-3" />
Projects
</MDBListGroupItem>
</NavLink>
<NavLink to="/tables" activeClassName="activeClass">
<MDBListGroupItem className="bgc">
<MDBIcon icon="table" className="mr-3" />
Tables
</MDBListGroupItem>
</NavLink>
<NavLink to="/inventory" activeClassName="activeClass">
<MDBListGroupItem className="bgc">
<MDBIcon icon="fas fa-truck-loading" className="mr-3" />
Inventory
</MDBListGroupItem>
</NavLink>
<NavLink to="/404" activeClassName="activeClass" />
</MDBListGroup>
</div>
);
};
export default sideNavigation;
thanks in advance for your help guys...
When I made a small change to my code, I could eliminate that weird behavior.
the changes were only made to my App.js file.
please find the changes below
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import MainPage from "./Mainpage";
import LoginPage from "./components/pages/LoginPage";
import "./styleFiles/index.css";
class App extends Component {
render() {
return (
<div className="flexible-content ">
<Switch>
<Route path="/Main" exact component={MainPage} />
<Route path="/login" component={LoginPage} />
<Route component={MainPage} />
</Switch>
</div>
);
}
}
export default App;
I added a switch tag and a Generic Not Found route component to my app.js file.
I am still a newbie to React. So here I am rendering the root component with two routes: Home and About located in functional components: home.js and about.js respectively. However, even after using exact attribute and , the root component keeps on rendering above. I still cannot figure out how to not render the root component when I am redirecting to any of the mentioned routes?
Heres the live demo: https://codesandbox.io/s/vmz6zwq0k7
The Route component is acting like a "placeholder" for the component you want to render when the URL matches. everything above it (parents and siblings) wont get affected.
Given this code example:
render() {
return (
<BrowserRouter>
<div className="App">
<Link to="/home"> Home </Link>{" "}
|
<Link to="/about"> About Us </Link>{" "}
<div>
<Route exact path="/home" component={Home} />
<Route exact path="/about" component={About} />
</div>
</div>
</BrowserRouter>
);
}
This line of code:
<Route exact path="/home" component={Home} />
Is only a "placeholder" for the Home component. It won't render anything only when the path is matching "/home".
When the path will match, the Route component will render the passed component, The Home component in this case.
It will not affect the entire app tree, and for a good reason!
If the entire app would get re-rendered and replaced with the Home component you would loose the navigation links.
I had the same problem looking at the react-routing getting started portion here. https://reactrouter.com/web/guides/quick-start
I placed my Router/BrowserRouter in my App component. Instead place the router in your index.js file like so
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
Then your app component can look like so and the root route wont be matched if about or users is matched.
import React from "react";
import {
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}