Nested routing in react is not rendering nested component - javascript

Nested routing is not working. 'Landing' And 'home' components showing properly but nested components are not rendering.
The layout component is directly imported in app.js
there is no error in the console but nested components such as 'Feed' and 'Myprofile' are not rendering.
see the code
import React from 'react';
import { Route, Switch, BrowserRouter as Router} from 'react-router-dom';
import Sidebar from '../componants/Sidebar'
import Navbar from '../componants/Navbar';
import PathRouter from '../Routers/PathRouters'
import Landing from '../pages/Landing';
const Home=()=>{
return(
<>
<div className="container-fluid">
<Navbar />
<div className="rows row">
<div className='col-3'>
<Sidebar />
</div>
<div className="col-9 ">
<div className="content">
<Switch>
{PathRouter.map((prop, key) => {
return (
<Route
exact path={prop.path}
component={prop.component}
key={key}
/>
);
}
)}
</Switch>
</div>
</div>
</div>
</div>
</>
)
}
const Layout = () => {
return (
<>
<Router>
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/home' component={Home} />
</Switch>
</Router>
</>
)
}
export default Layout;
This is Pathrouter.js
import Feed from '../pages/Feed';
import Answer from '../pages/Answer';
import Addquestion from '../componants/Addquestion';
import Myprofile from '../componants/Myprofile';
var PathRouter = [
{
path: '/home/feed',
name: 'Feed',
component: Feed
},
{
path: '/home/answer/:q_id',
name: 'answer',
component: Answer
},
{
path: '/home/addquestion',
name: 'addquestion',
component: Addquestion
},
{
path: '/home/myprofile',
name: 'myprofile',
component: Myprofile
}
]
export default PathRouter;

In the Layout component the line <Route exact path='/home' component={Home} /> is breaking your nested routes. For the nested route to render the parent route must also render, since '/home/feed' does not exactly match '/home' the parent route will not be rendered. Remove exact from the '/home' route. – Jacob Smit

Related

Unable to change view on sidebar button click - React

I'm pretty new to react. It's been only a few days since I started react.
I have a question regarding routing. I'm trying to change the main content on the sidebar button click. I think I'm doing something wrong with linking pages right.
In below Sidebar.js class, I am linking the dashboard page on button click with to="/admin/dashboard"
Below is the Sidebar.js class
import React from "react";
import { Link } from "react-router-dom";
const Sidebar = () => {
return (
<nav className="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div className="sb-sidenav-menu">
<div className="nav">
<div className="sb-sidenav-menu-heading">Core</div>
<Link className="nav-link" to="/admin/dashboard"> // <<<--- Here I'm linking button
<div className="sb-nav-link-icon">
<i className="fas fa-tachometer-alt"></i>
</div>
Dashboard
</Link>
......... Similar type of code .......
</div>
</div>
<div className="sb-sidenav-footer">
<div className="small">Logged in as:</div>
Ecommerce React Laravel admin
</div>
</nav>
);
};
export default Sidebar;
Below is App.js
import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import MasterLayout from "./layouts/admin/MasterLayout";
import Home from "./components/frontend/Home";
function App() {
return (
<div className="App">
<h1>Hello</h1>
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/admin/*"
name="Admin"
element={<MasterLayout />}
/>
</Routes>
</Router>
</div>
);
}
export default App;
Below is the MasterLayout.js
import React from "react";
import { Navigate, Route, Routes, Router } from "react-router-dom";
import "../../assets/admin/css/styles.css";
import "../../assets/admin/js/scripts";
import Navbar from "./Navbar";
import Sidebar from "./Sidebar";
import Footer from "./Footer";
import routes from "../../routes/routes";
import Dashboard from "../../components/admin/Dashboard";
const MasterLayout = () => {
return (
<div className="sb-nav-fixed">
<Navbar />
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<Sidebar />
</div>
<div id="layoutSidenav_content">
<main>
<Routes>
{ routes.map((route, idx) => {
return (
route.element && (
<Route
key={idx}
path={route.path}
name={route.name}
element={route.element}
/>
)
);
})}
</Routes>
</main>
</div>
</div>
</div>
);
};
export default MasterLayout;
Below is the routes.js class
const routes = [
{
path: "/admin/dashboard",
name: "Dashboard",
element: <Dashboard />,
},
{
path: "/admin/profile",
name: "Profile",
element: <Profile />,
},
{ path: "/", name: "Admin", element: <Dashboard /> },
];
Below is dashboard.js
import React from "react";
function Dashboard() {
return <h1>I'm Dashboard</h1>;
}
export default Dashboard;
Below is the file directory
This link is changing as desired. Browser URL look as expected when clicking the link
The element prop takes a ReactNode, a.k.a. JSX. Instead of passing a reference to a React component pass it as JSX. The routes should also be relative from the /"admin/*" path rendered in App.
const routes = [
{ path: "/", name: "Admin", element: <Dashboard /> },
{
path: "dashboard",
name: "Dashboard",
element: <Dashboard />,
},
{
path: "profile",
name: "Profile",
element: <Profile />,
},
];

React-Router: Nested route not rendering component

This is a simplified reproduction of the problem: The child with the nested URL does not render.
My file structure is basically this:
-App
--Home
--Pageone
---Childone
I can render Home or Pageone from App, then I can render Home or Pageone from Pageone or Home respectively, but I cannot render Childone from its 'parent page' Pageone. I am not quite sure what is done wrong.
The code is shared below, and this sandbox
App.jsx
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Pageone from "./Pageone";
import Home from "./Home";
export default function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/pageone">
<Pageone />
</Route>
</Switch>
</BrowserRouter>
);
}
Home.jsx
import { Link } from "react-router-dom";
const Home = () => {
return (
<div>
<p>This is HOME!</p>
<Link to="/pageone">Pageone</Link>
</div>
);
};
export default Home;
Pageone.jsx
import { Link, Route, useRouteMatch } from "react-router-dom";
import Childone from "./Childone";
const Pageone = () => {
const { path, url } = useRouteMatch();
return (
<div>
<Route exact path={path}>
<PageoneContent url={url} />
</Route>
<Route exact path={path + "/childone"}>
<Childone />
</Route>
</div>
);
};
const PageoneContent = (props) => {
return (
<div>
<p>This is pageone!</p>
<Link to="/">Go back Home</Link>
<br />
<Link to={props.url + "/childone"}>Go to Child One</Link>
</div>
);
};
export default Pageone;
Childone.jsx
import { Link } from "react-router-dom";
const Childone = () => {
return (
<div>
<p>This is Child one!</p>
<Link to="/">Go back Home</Link>
</div>
);
};
export default Childone;
As far as I know you need to use another Switch for routes, otherwise react will have no idea how to match that route path.
<div>
<Route exact path={path}>
Should be:
<Switch>
<Route exact path={path}>

Getting React Props after sending it from Route

I Am Sending React Component from a route as mention in this Link
<Route path='/StartCompaign' render={(props) => <CampaignStart {...props} isDashboard={true} /> } />
and i am getting props in another Component like
{props.childern.render.isDashboard ? <Header /> : "NO" }
APP.JSX file
import React from 'react';
import { Route, Switch } from 'react-router';
import Layout from './components/Layout';
import Home from './components/Dynamic/Home';
import Filter from './components/Dynamic/Filter';
import { AboutCampaign } from './components/Dynamic/AboutCampaign';
import { CampaignStart } from './components/Dynamic/CompaignStart';
import NotFound from './NotFound';
import {SignUp} from './components/Static/SignUp';
import { Login } from './components/Static/Login';
import Dashboard from './components/Dashboard'
import { withCookies } from 'react-cookie';
class App extends React.Component {
render() {
return (
<Switch>
<Layout>
<Route exact path='/' component={Home} />
<Route path='/filter' component={Filter}/>
<Route path='/Campaign/:campaignId' component={AboutCampaign}/>
<Route path='/SignUp' component={SignUp}/>
<Route path='/Login' component={Login}/>
<Route path='/Dashboard' render={(props) => <Dashboard {...props} isDashboard={true} /> } />
<Route path="" component={NotFound} />
</Layout>
</Switch>
);
}
}
export default withCookies(App);
Layout.JSX
import React from 'react';
import { Container } from 'reactstrap';
import Header from './Static/Header';
import Footer from './Static/Footer';
import TopNavigation from './Component/DashBoard/TopNavigation'
export default props => (
<div>
{props.isDashboard ? <Header /> : <TopNavigation /> }
<Container>
{props.children}
</Container>
<Footer />
</div>
);
I am trying to change the <Header/> and <TopNavigation /> in react application when the specfic route is called but props.isDashboard seemed undefined
It's because you are sending props to <Dashboard/> component
<Dashboard {...props} isDashboard={true} />
but not to <Layout /> component.
If Layout component needs to receive isDashboard props you need to pass it like
<Layout isDashboard={true} />
As Layout is parent component, if child components also needs the props you could always pass those to children easily.

How to implement dynamic pages in React.js?

import React, { Component } from "react";
import { FormattedMessage } from "react-intl";
import { connect } from "react-redux";
class Project extends Component {
render() {
return (
<div
className={
"ih-item square effect6 from_top_and_bottom grid-item " +
this.props.category +
" " +
this.props.widthClass
}
>
<FormattedMessage id="route.project">
{route => {
return (
<a href={"/" + route + this.props.url}>
<div className="img">
<img src={this.props.mainImage} alt="img" />
</div>
<div className="info">
<h3>{this.props.header}</h3>
<p>{this.props.description}</p>
</div>
</a>
);
}}
</FormattedMessage>
</div>
);
}
}
const mapStateToProps = state => {
return {
projects: state.project.projects
};
};
export default connect(
mapStateToProps,
{}
)(Project);
How to implement projects' pages and custom URL for every one. I suppose custom URLs have to be done with MongoDB, but how to implement it in reactjs. That is third day of my research, but mostly I found complicated code
Thanks for every answer
You would most likely use a client-side navigation package such as React-Router to accomplish this.
In order to set up a basic router, you need to define routes and views for those routes in the following fashion, where the "path" prop refers to your desired endpoint and "component" being the desired view:
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const BasicExample = () => (
<Router>
<div>
{/* Navigation menu */}
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<hr />
{/* Routes */}
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>
);
These routes can also be dynamically-generated using an array of routes, such as the following (defined in your component state):
routes = [
{
path: "/",
exact: true,
component: Home
},
{
path: "/bubblegum",
component: () => <div>bubblegum!</div>,
},
{
path: "/shoelaces",
component: Shoelaces
}
and then rendered in React using .map():
{this.state.routes.map(route => (
<Route exact={route.exact||false} path={route.path} component={route.component} />
))}
I think you need to install react-router-dom.
Second, please use template strings.

React-router v4, URL changing but component doesn't render

I've tried everything but fail to render component when URL changes. No error messages nothing, react-redux is installed but not using it yet, so it can't be the problem. When I check it from to Google chrome React dev tools, nothing happens, there is no match, history vs anything. I couldn't find a solution, is there any way to make it work?
https://codesandbox.io/s/vm3x9n4k67
Here is my NavBar.js. I import NavLink from react-router-dom and implement these
import React from 'react'
import classes from "./NavBar.css";
import { NavLink } from 'react-router-dom';
const NavBar = (props) => {
return (
<div className={classes.NavBar}>
<h1 className={classes.NavBar_list} >foodbase</h1>
<ul className={classes.NavBar_list}>
<NavLink to="/auth"> <li className={classes.NavBar_list_item}>Signin</li></NavLink>
<NavLink to="/"><li className={classes.NavBar_list_item}>Main Page</li></NavLink>
</ul>
</div>
)
}
export default NavBar
this is my Layout.js render property:
render() {
let recipes = [];
if (this.state.recipes.length > 0) {
recipes = this.state.recipes;
}
return (
<div>
<NavBar/>
<SearchBox
onChangeHandler={this.onChangeHandler}
value={this.state.inputValue}
onSearchClick={this.onClickedHandler} />
<section className={classes.SearchSection}>
<ul className={classes.SearchResultArea}>
<SearchResults
Results={recipes}
></SearchResults>
</ul>
</section>
</div>
)
}
and finally app.js:
import React, { Component } from 'react';
import { Switch, Route, BrowserRouter, withRouter } from 'react-router-dom';
import Auth from './components/Auth/Auth';
import SearchBox from './components/SearchBox/SearchBox';
import Layout from './containers/Layout/Layout';
import './App.css';
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<Switch>
<Layout>
<Route path="/auth" component={Auth} />
<Route path="/" exact component={SearchBox} />
</Layout>
</Switch>
</BrowserRouter>
</div>
);
}
}
export default withRouter(App);
I assume that you need to put your Route components directly into Switch and don't forget to render children in Layout. So try this:
app.js:
class App extends Component {
render() {
return (
<div>
<BrowserRouter>
<Layout>
<Switch>
<Route path="/auth" component={Auth} />
<Route path="/" exact component={SearchBox} />
</Switch>
</Layout>
</BrowserRouter>
</div>
);
}
}
Layout.js
render() {
// ...
return (
<div>
<NavBar />
{ this.props.children } // <-- your route specific components
</div>
)
}

Categories