Not able to render react component in react router - javascript

I have a react application.
i have problem in routing of component
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from './app';
ReactDOM.render(
<App/>,
document.getElementById("root")
);
app.jsx
Here i am routing 2 component. Login and Main component. In Main component there are many router which will use for dashboard.
My Problem : In <Switch> the 1st <Route> can render but it's not rendering from 2nd router if i hardcode in url
http://localhost:3000/#/login == rendering
http://localhost:3000/#/main = Not rendering
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom';
import Login from './login';
import Main from './main';
import createBrowserHistory from 'history/createBrowserHistory';
const customHistory = createBrowserHistory();
class App extends Component {
constructor(props) {
super(props);
window.token = '';
}
render() {
return <div>
<Router>
<Switch>
<Route to="/login" component={Login} exact />
<Route to="/main" component={Main} exact/>
</Switch>
</Router>
</div>;
}
}
export default App;
main.jsx
import React, {Component} from 'react';
import ReactDOM from "react-dom";
import { HashRouter, Route, Switch } from "react-router-dom";
import indexRoutes from "routes/index.jsx";
import "bootstrap/dist/css/bootstrap.min.css";
import "./assets/css/animate.min.css";
import "./assets/sass/light-bootstrap-dashboard.css?v=1.2.0";
import "./assets/css/demo.css";
import "./assets/css/pe-icon-7-stroke.css";
import Login from './login';
class Main extends Component {
constructor(props) {
super(props);
}
render() {
return <HashRouter>
<Switch>
{indexRoutes.map((prop, key) => {
return <Route to={prop.path} component={prop.component} key={key} />;
})}
</Switch>
</HashRouter>;
}
}
export default Main;

Use
<Route path="/login" component={Login} exact />
Instead of to use path

<Route path="/login" component={Login} />
<Route path="/main" component={Main} exact/>
Use Path insted of To

Don't use exact attribute in main Route as shown below.
class App extends Component {
render() {
return <div>
<Router>
<Switch>
...
<Route to="/main" component={Main} />
</Switch>
</Router>
</div>;
}
}

There are two problems with your code
First in your app.jsx file:
<Switch>
<Route
to="/login" // <== should be path="/login"
component={Login}
exact
/>
<Route
to="/main" // <== should be path="/main"
component={Main}
exact // <== remove exact prop for the nested routes to work
/>
</Switch>
Here to prop actually belongs to the <Link/> component provided by react-router not the <Route /> component, It should be path prop.
If you want to render child routes within <Route /> component then we never use exact prop on the Parent <Route /> component.
Second in your main.jsx file:
indexRoutes.map((prop, key) => {
return (
<Route
to={prop.path} // <== should be path={prop.path}
component={prop.component}
key={key} />;
);
})
Again change to prop to path prop.

Related

React Router: Component not getting displayed

I have just started with React and not able to get the router working. Below is the code for router. If I use the individual components without the router, they are displayed on the screen. But with router I don't get any text on the screen across any of the paths.
Please let me know if I am missing something. Below is the code:
import { Route } from 'react-router-dom';
import AllMeetupsPage from './pages/AllMeetups';
import NewMeetupPage from './pages/NewMeetup';
function App() {
return (
<div>
<Route path='/' exact>
<AllMeetupsPage />
</Route>
<Route path='/new-meetup'>
<NewMeetupPage />
</Route>
</div>);
}
export default App;
A route needs to be a descendent of router component. I'm not sure which version of react-router you're using, but this will be a BrowserRouter and Routes component for react-router v6 and on v4/v5 it'll be a BrowserRouter
Here's some examples:
v6:
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import AllMeetupsPage from './pages/AllMeetups';
import NewMeetupPage from './pages/NewMeetup';
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path="/" exact element={<AllMeetupsPage />}/>
<Route path="/new-meetup" element={<NewMeetupPage />}/>
</Routes>
</BrowserRouter>
</div>);
}
export default App;
You missed using Switch component
import { Route , Switch } from 'react-router-dom';
function App() {
return (
<div>
<Switch>
<Route path='/' exact>
<AllMeetupsPage />
</Route>
<Route path='/new-meetup'>
<NewMeetupPage />
</Route>
</Switch>
</div>);
}
export default App;

React-router-dom not compiling components

I have problem with router-dom. I am working according to youtube tutorial, I cannot resolve below error:
[landingPageLayout] is not a component. All component children of must be a or <React.Fragment>. I would be greateful for some guidance.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
App.js
import './App.css';
import { Routes, Route } from 'react-router-dom';
import landingPageLayout from './components/layouts/landingPageLayout';
import homePage from './components/pages/homePage';
const App = () => {
return (
<Routes>
<landingPageLayout>
<Route path="/">
<homePage/>
</Route>
</landingPageLayout>
</Routes>
);
}
landingPageLayout.js
import React from 'react';
import Header from '../navigation/header';
const landingPageLayout = ({...otherProps}) => {
return (
<div>
<Header/>
</div>
)
}
export default landingPageLayout;
As Nicholas said in comments, your react components should always be capitalized.
Other than that, Routes component only accepts or <React.Fragment> as children so you can't add your layout like that. What you can do is something like this:
const App = () => {
return (
<Routes>
<Route
path='/*'
element={
<LandingPageLayout>
<HomePage />
</LandingPageLayout>
}
/>
</Routes>
);
}
If you have several routes that need this layout, you should replace HomePage with another component that has all the routes. For example we can call it PrivateRoutes. Then in code above you replace <HomePage /> with <PrivateRoutes /> and then your PrivateRoutes component should look like this:
const PrivateRoutes = () => {
return (
<Routes>
<Route path="home" element={<HomePage />} />
<Route path="page1" element={<Page1 /> />
//rest of routes
</Routes>
);
}

React Router Not Working Like I Need It Too

Im trying to figure out how to get my navigation bar setup as most of the UI is coming together. I have setup my index.js and also a Route.js and then linked them with my different components like so:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import { Auth0Provider } from "./react-auth0-spa.js";
import { useAuth0 } from "./react-auth0-spa";
import Routes from "./Routes"
import config from "./utils/auth_config.json";
import { BrowserRouter } from "react-router-dom";
// A function that routes the user to the right place
// after login
const onRedirectCallback = appState => {
history.push(
appState && appState.targetUrl
? appState.targetUrl
: window.location.pathname
);
};
ReactDOM.render(
<Auth0Provider
domain={config.domain}
client_id={config.clientId}
redirect_uri={window.location.origin}
onRedirectCallback={onRedirectCallback}
>
<BrowserRouter>
<Routes />
</BrowserRouter>
</Auth0Provider>,
document.getElementById("root")
);
Routes.js
import React, { Component } from "react";
import { Router, Route, Switch, BrowserRouter } from "react-router-dom";
import {Link } from "react-router-dom";
import Profile from "./components/user/Profile";
import PrivateRoute from "./components/user/PrivateRoute";
import history from "./utils/history.js";
import HomePage from "./modules/HomePage.js";
import ProductPage from "./modules/ProductPage";
class Routes extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>
)
}
}
export default Routes;
but when i reload my site it just continues to say localhost:8080/ProductPage like its suppose to be the default, then when i manually enter localhost:8080/ and click on a button after linking it with
<Link to="ProductPage">
it will show on the tab localhost:8080/ProductPage but wont actually redirect me to the other component, i am just wondering what i am doing wrong?
Issue
You have your "home" route listed first in the Switch.
Switch
Renders the first child <Route> or <Redirect> that matches the location.
"/" is less specific and matches basically all routes, so even though the URL is "/ProductPage", "/" still matches it and HomePage is rendered.
Solution
Either move it after the other more specific routes or use the exact prop on it.
<Router history={history}>
<Switch>
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
<Route path="/" component={HomePage} />
</Switch>
</Router>
or
<Router history={history}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/ProductPage" component={ProductPage} />
<PrivateRoute path="/profile" component={Profile} />
</Switch>
</Router>

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.

React Router Duplicate routes on Back Button

I have a react app. It is working fine. It uses redux,react-router 3. The routes work fine, but when I press the back button, they route gets duplicated. For example from localhost:3000/admin/main which I am currently, when I go back, it goes to localhost:3000/admin/admin/main, which return not found.
Here is my routes code:
export default (
<Route path="/" component={App}>
<Route path="home" component={requireNoAuthentication(HomeContainer)} />
<Route path="login" component={requireNoAuthentication(LoginView)} />
<Route exact path="admin/user" component={requireAuthentication(UserView)} />
<Route exact path="admin/main" component={requireAuthentication(UsersListView)} />
<Route path="secure" component={requireAuthentication(CustomerView)} />
<Route exact path="*" component={DetermineAuth(NotFound)} />
</Route>
);
I also get a console error: Adjacent JSX elements must be wrapped in an enclosing tag. If anyone can help it would be great thanks!!
Your HOC wrappers (requireNoAuthentication and requireAuthentication) and using exact (I think this might a react-router v4 only feature?) might be messing with your route history. Try restructuring your routes so that all of them fall under App -- some of the routes fall under RequireAuth, while the rest are public.
As a side note: you can avoid using React.cloneElement with passed down class methods and state by using Redux instead.
routes/index.js
import React from "react";
import { browserHistory, IndexRoute, Router, Route } from "react-router";
import App from "../components/App";
import Home from "../components/Home";
import Info from "../components/Info";
import ShowPlayerRoster from "../components/ShowPlayerRoster";
import ShowPlayerStats from "../components/ShowPlayerStats";
import Schedule from "../components/Schedule";
import Sponsors from "../components/Sponsors";
import RequireAuth from "../components/RequireAuth";
export default () => (
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route component={RequireAuth}>
<IndexRoute component={Home} />
<Route path="roster" component={ShowPlayerRoster} />
<Route path="roster/:id" component={ShowPlayerStats} />
<Route path="schedule" component={Schedule} />
</Route>
<Route path="info" component={Info} />
<Route path="sponsors" component={Sponsors} />
</Route>
</Router>
);
index.js
import React from "react";
import { render } from "react-dom";
import App from "../routes";
import "uikit/dist/css/uikit.min.css";
render(<App />, document.getElementById("root"));
components/App.js
import React, { Component, Fragment } from "react";
import { browserHistory } from "react-router";
import Header from "./Header";
export default class App extends Component {
state = {
isAuthenticated: false
};
isAuthed = () => this.setState({ isAuthenticated: true });
unAuth = () =>
this.setState({ isAuthenticated: false }, () => browserHistory.push("/"));
render = () => (
<Fragment>
<Header
isAuthenticated={this.state.isAuthenticated}
unAuth={this.unAuth}
/>
{React.cloneElement(this.props.children, {
isAuthenticated: this.state.isAuthenticated,
isAuthed: this.isAuthed
})}
</Fragment>
);
}
components/RequireAuth.js
import React, { Fragment } from "react";
import Login from "./Login";
export default ({ children, isAuthenticated, isAuthed }) =>
!isAuthenticated ? (
<Login isAuthed={isAuthed} />
) : (
<Fragment>{children}</Fragment>
);

Categories