i've been following an online course about react but it's a bit dated and i've been struggling through all the lessons to understand the concepts explained while applying the new syntax instead of the the one shown in the videos. i've always more or less managed but now i'm stuck because, after adding the react router dom web app, my pages don't render anymore. no errors nor warnings are shown and no matter how much i look, i can't seem to find the mistake. my main right now looks like this:
import React from 'react';
import Header from './header';
import MyPlacesList from './myplaceslist.js';
import Footer from './footer';
import CreatePlace from './createPlace.js';
import * as attAPI from '../utils/attractionsAPI';
import { Router, Route } from 'react-router-dom';
class Main extends React.Component{
state = {
attractions: [],
}
componentDidMount(){
attAPI.getAll().then((attractions) => {
this.setState({attractions})
})
}
removePlace = (attraction) => {
this.setState((state) => ({
attractions: state.attractions.filter((attr) => attr.id !== attraction.id)
}))
attAPI.remove(attraction);
}
render(){
return (
<Router>
<Fragment>
<Header titolo = 'My Places' sottotitolo = 'I miei posti preferiti'/>
<Route exact path = '/' render = {() => (
<MyPlacesList attractions = {this.state.attractions}
onRemovePlace = {this.removePlace} />
)}/>
<Route path = '/create' render = {() => (
<CreatePlace />
)}/>
<Footer />
</Fragment>
</Router>
)
}
}
export default Main;
and this is the header:
import React from 'react';
import AppBar from '#mui/material/AppBar';
import Box from '#mui/material/Box';
import Toolbar from '#mui/material/Toolbar';
import Typography from '#mui/material/Typography';
import IconButton from '#mui/material/IconButton';
import Icon from '#mui/material/Icon';
import AddCircleIcon from '#mui/icons-material/AddCircle';
import { Link } from 'react-router-dom';
class Header extends React.Component{
render(){
// return <nav>
// <div className = "nav-wrapper">
// {this.props.titolo}
// </div>
// </nav>
return <Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<Typography
variant="h6"
noWrap
component="div"
sx={{ flexGrow: 1, display: { xs: 'none', sm: 'block' } }}
>
{this.props.titolo}
</Typography>
<Link to = '/create'>
<IconButton>
<AddCircleIcon />
</IconButton>
</Link>
</Toolbar>
</AppBar>
</Box>
}
}
export default Header;
before adding react router dom i was using the state to call the components MyPlacesList/CreatePlace (createPlace only gets shown when i click on a button) and it worked just fine, the problem appeared after i tried to use <Route>. any ideas in how could i fix this? thank you in advance!
EDIT - here's my index page too:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Main from './components/main';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<Main/>
</BrowserRouter>, document.getElementById('root'));
Things to correct
Use React.Fragment instead of just Fragment or import from react.
Add All Routes between Routes component.
You have already add Router or BrowserRouter in index.js so don't need to add again.
There is a change in nesting in version 5.
So ultimately the nesting should be in version 6
<BrowserRouter>
<Routes>
<Route>
<Route>
</Routes>
</BrowserRouter>
import MyPlacesList from "./myPlacesList.js";
import CreatePlace from "./createPlace.js";
import { Route, Routes } from "react-router-dom";
class App extends React.Component {
render() {
return (
<React.Fragment>
<div>Some Header component</div>
<Routes>
<Route
exact
path="/"
render={() => (
<MyPlacesList
attractions={this.state.attractions}
onRemovePlace={this.removePlace}
/>
)}
/>
<Route path="/create" render={() => <CreatePlace />} />
</Routes>
</React.Fragment>
);
}
}
export default App;
Related
Okay so I've gone through some answers provided to this problem here but seems not to fix my issue. SO I am making use of react-router-dom 6 for my routing. The base "/" route works as expected by when I visit another route in a different file, it goes blank and show no routes matched loaction "/path name". But if I place a "*" as route path, everything works fine but this will become a problem if I'm handling authentication. Below is my code, I sincerely need some tips:
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "antd/dist/antd.css";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
App.js
import "./App.css";
import { DASHBOARD, LOGIN } from "./routes";
import { Routes, Route } from "react-router-dom";
import { LoginPage } from "./pages";
import DashBoardLayout from "./pages/dashboard-layout/DashBoardLayout";
function App() {
return (
<div className="App">
<Routes>
<Route path={DASHBOARD} element={<DashBoardLayout />} />
<Route exact path={LOGIN} element={<LoginPage />} />
</Routes>
</div>
);
}
export default App;
route.js
export const LOGIN = "/";
export const DASHBOARD = "*";
export const CREATE_JOB = "/create";
export const EDIT_JOB = "/edit";
dashboardlayout.js
import "./style.scss";
import { Layout, Menu } from "antd";
import { Routes, Route, Link } from "react-router-dom";
import TopNavigation from "../../components/top-navigation/TopNavigation";
import { CREATE_JOB, EDIT_JOB } from "../../routes";
import { CreateJobPage, EditJobPage } from "../../pages";
import DashBoardIcon from "../../assets/dashboard_icon.svg";
import JobsIcon from "../../assets/jobs_icon.svg";
import UsersIcon from "../../assets/users_icon.svg";
const { Content, Sider } = Layout;
const { SubMenu } = Menu;
const DashBoardLayout = () => {
return (
<Layout className="dashboard__container">
<TopNavigation />
<Layout>
<Sider width={300} className="dashbord__sidebar">
<Menu defaultSelectedKeys={["1"]}>
<Menu.Item key="1">
<img src={DashBoardIcon} alt="dashboard icon" />
Dashbord
</Menu.Item>
<Menu.Item key="2">
<Link to={CREATE_JOB}>
<img src={JobsIcon} alt="jobs icon" />
Jobs
</Link>
</Menu.Item>
<Menu.Item key="3">
<Link to={EDIT_JOB}>
<img src={UsersIcon} alt="users icon" />
Users
</Link>
</Menu.Item>
</Menu>
</Sider>
<Layout style={{ padding: "24px 24px" }}>
<Content
style={{
padding: 24,
margin: 0,
justifyContent: "center",
display: "flex",
}}
>
<Routes>
<Route path={CREATE_JOB} element={<CreateJobPage />} />
<Route path={EDIT_JOB} element={<EditJobPage />} />
</Routes>
</Content>
</Layout>
</Layout>
</Layout>
);
};
export default DashBoardLayout;
So any tips on how I can go about this? I want to remove that (*) from the route because it is causing problems in authentication.
Thanks for your anticipated assistance
Apparently, I solved this issue by making use of one Routes import in the dashoadlayout. React was finding it difficult to locate the new route in the dashboardlayout and that of the App.js file. And what about the App.js file? well I used a conditional rendering with my userToken to render each page if the user is logged in or not while removing the routes there and its working fine.
App.js code-
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./screens/HomeScreen";
const App = () => {
return (
<Router>
<Header />
<main className='py-3'>
<Container>
<HomeScreen />
</Container>
</main>
<Footer />
</Router>
);
};
export default App;
My app.js was like this and everything was working fine. But after that I added Route tag and the code become like this
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./screens/HomeScreen";
const App = () => {
return (
<Router>
<Header />
<main className='py-3'>
<Container>
<Route exact path='/' component={HomeScreen} />
</Container>
</main>
<Footer />
</Router>
);
};
export default App;
But after adding Route, HomeScreen is not rendering?
Can anybody tell me why this is happening?
In react-router-dom v6 the Route component must be rendered into a Routes component, and the routed components are rendered on the element prop as a ReactElement (a.k.a. JSX) since the component, and render and children function props no longer exist.
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import { Container } from "react-bootstrap";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./screens/HomeScreen";
const App = () => {
return (
<Router>
<Header />
<main className='py-3'>
<Container>
<Routes>
<Route path='/' element={<HomeScreen />} />
</Routes>
</Container>
</main>
<Footer />
</Router>
);
};
React RouterLink not working. i have a component like profile.js i want to redirect that component by onclick. so o tried many way to do this. and i dont understand router and router as link. can you refer me some exact documentation about this.
here is my code:
//Nav bar
<Transitions in={open} {...TransitionProps}>
<MainCard>
<CardContent>
<List component="nav" className={classes.navContainer}>
<ListItem className={classes.listItem}
sx={{ borderRadius: theme.palette.borderRadius + "px", }}
selected={selectedIndex === 0}
onClick={(event) => handleListItemClick(event, 0)}
component={React.forwardRef((props, ref) => (
<RouterLink {...props} to="../Profile/profile"/>
))} >
<ListItemIcon>
<IconSettings stroke={1.5} size="1.3rem" />
</ListItemIcon>
<ListItemText
primary={<Typography variant="body2">Account Settings</Typography> }/>
</ListItem>
</CardContent>
</MainCard>
</Transitions>
This component need to redirect when i click menu.
//Profile.js
import React from "react";
import "./profile.css";
function profile() {
return (
<card>
<div class="main-content">
<p>Profile</p>
</div>
</card>
)};
Routes:
//CustomRoutes.js
import React from "react";
import { Route } from "react-router-dom";
import Profile from "./component/layout/MainLayout/Header/Profile/profile";
export default [
<Route path="/profile" exact component={Profile} />,
];
App.js
//App.js
import customLayout from "./component/layout/customLayout/customLayout";
import profile from "./component/layout/MainLayout/Header/Profile/profile";
import AdminBuilder from "./AdminBuilder";
import React, { Component, createContext } from "react";
class App extends Component {
render() {
return (
<AdminBuilder profile={profile} />
);
}
In the main file, i think it would be app.js
you need to tell your profile path to which location it should go. for example:
<Route path="/profile" exact component={Profile} />
Now you can use this /profile path into your
<RouterLink {...props} to="../Profile/profile"/>
but its better to use <Link to="/profile"> </Link>
Hope it make since.
#Update:
import React from "react";
import { Route } from "react-router-dom";
import Profile from "./component/layout/MainLayout/Header/Profile/profile";
**what is this export default?**
export default [
<Route path="/profile" exact component={Profile} />,
];
#Update2
in your app please make it like this>
import React from 'react'
import customLayout from "./component/layout/customLayout/customLayout";
import profile from "./component/layout/MainLayout/Header/Profile/profile";
import AdminBuilder from "./AdminBuilder";
import React, { Component, createContext } from "react";
export default function App() {
return (
<div>
<AdminBuilder profile={profile} />
</div>
)
}
Hi i am trying to change the route of my website to go to Contact, when the menu is clicked.
Whenever i press the button for the homepage which is "Forside", the routing works perfectly.
But as soon as i press the button for the contact which is "Kontakt", the url changes and no component renders. But if i refresh the page, it shows up..
Any ideas what is wrong with my code, or any way to fix it?
All help will be appreciated thanks.
My App.js
import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Forside from './forside';
import Kontakt from './Kontakt';
import Header from './Header'
const App = () => {
return(
<Router>
<div>
<Header/>
<Switch>
<Route exact path="/" component={Forside}/>
<Route path="/kontakt" component={Kontakt}/>
</Switch>
</div>
</Router>
)
}
export default App
And this is where i link to the different routes.
import React, { useState } from 'react';
import './header.css'
import { makeStyles } from '#material-ui/core/styles';
import BottomNavigation from '#material-ui/core/BottomNavigation';
import BottomNavigationAction from '#material-ui/core/BottomNavigationAction';
import ContactMailIcon from '#material-ui/icons/ContactMail';
import LocationOnIcon from '#material-ui/icons/LocationOn';
import {Link} from 'react-router-dom';
const useStyles = makeStyles({
root: {
width: 500,
},
});
const Header = () => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
return(
<div className="hed">
<h1 className="logo"><span>IT</span> ARBEJDE.DK</h1>
<BottomNavigation
value={value}
className="nav"
onChange={(event, newValue) => {
setValue(newValue);
}}
showLabels
className={classes.root}
>
<Link to="/">
<BottomNavigationAction label="Søg job" icon={<LocationOnIcon />} />
</Link>
<Link to="/kontakt">
<BottomNavigationAction label="Kontakt" icon={<ContactMailIcon/>} />
</Link>
</BottomNavigation>
</div>
)
}
export default Header
add exact to it to your route
<Route exact path="/kontakt" component={Kontakt}/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Since i didn't get a answer, i have figured it out on my own. So i would just like to share the solution, for other people who maybe are expecting the same bug.
I fixed the problem, by restructuring my code.
I placed my router inside the index.js component like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {BrowserRouter as Router} from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<Router>
<App/>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
Then placed the Header code inside my App.js, instead of having the Component rendering.
So i refactored the code like this:
import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import Kontakt from './Kontakt';
import Forside from './forside';
import { makeStyles } from '#material-ui/core/styles';
import BottomNavigation from '#material-ui/core/BottomNavigation';
import BottomNavigationAction from '#material-ui/core/BottomNavigationAction';
import ContactMailIcon from '#material-ui/icons/ContactMail';
import LocationOnIcon from '#material-ui/icons/LocationOn';
import {Link} from 'react-router-dom';
import './header.css'
const useStyles = makeStyles({
root: {
width: 500,
},
});
const App = () => {
const classes = useStyles();
const [value, setValue] = React.useState(0);
return(
<div>
<div className="header-container">
<h1 className="logo"><span>IT</span> ARBEJDE.DK</h1>
<BottomNavigation
value={value}
className="nav"
onChange={(event, newValue) => {
setValue(newValue);
}}
showLabels
className={classes.root}
>
<BottomNavigationAction label="Søg job" component={Link} to="/" icon={<LocationOnIcon />} />
<BottomNavigationAction label="Kontakt" component={Link} to="/kontakt" icon={<ContactMailIcon/>} />
</BottomNavigation>
</div>
<Switch>
<Route exact path="/" component={Forside}/>
<Route exact path="/kontakt" component={Kontakt}/>
</Switch>
</div>
)
}
export default App
I'm new to react and trying to manage the navigation in my web app with react-router.
I must be doing something wrong though, because my whole DOM is disappearing. Everything's fine while I set up the router:
Container.js
import React, {Component} from 'react';
import SideBar from "./sidebar/SideBar";
import Pagina from "./content/Pagina";
import {
BrowserRouter as Router,
NavLink
} from 'react-router-dom'
import NavRoutes from "./NavRoutes";
class Container extends Component {
render() {
return (
<div id="MyLearningContainer" className ="container-fluid">
<SideBar/>
<Pagina/>
<Router>
{NavRoutes}
</Router>
</div>
);
}
}
export default Container;
NavRoutes.js
import React from 'react';
import {
Route
} from 'react-router-dom';
import Dashboard from "./content/Dashboard";
import Utenti from "./content/Utenti";
const navRoutes = (
<Route path="/" component= {Dashboard}>
<Route path="utenti" component = {Utenti} />
</Route>
);
export default navRoutes;
The problem arises when I make my SideBarItem generate a <NavLink> inside its usual <li>:
SideBarItem.js
import React, {Component} from 'react';
import {
NavLink
} from 'react-router-dom'
const defaultClass = {
color: '#00338D',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 20,
paddingRight: 20
};
const activeClass = {
color: '#fff',
backgroundColor: '#428bca',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 20,
paddingRight: 20
};
class SideBarItem extends Component {
render() {
return (
<li>
<NavLink to={("/" + this.props.title).toLowerCase()}>
<span className={this.props.glyph}></span> {this.props.title}
</NavLink>
</li>
);
}
}
SideBarItem.defaultProps = {
title: 'Undefined',
glyph: 'glyphicon-home'
}
export default SideBarItem;
When I save this, the whole DOM just disappears and nothing gets rendered anymore!
Update
I edited the Container.js so that SideBar is now a child of Router.
class Container extends Component {
render() {
return (
<div id="MyLearningContainer" className="container-fluid">
<Router>
<div>
<SideBar/>
{NavRoutes}
</div>
</Router>
</div>
);
}
}
Now the DOM renders just fine, but clicking on the NavLink won't make the route change: it stays on Dashboard...
I managed to get the router working!
Following thenormalsquid's advice, I edited the Container.js so that SideBar became a child of Router.
class Container extends Component {
render() {
return (
<div id="MyLearningContainer" className="container-fluid">
<Router>
<div>
<SideBar/>
{NavRoutes}
</div>
</Router>
</div>
);
}
}
Then I edited NavRoutes.js, that wasn't pointing at the right links.
import React from 'react';
import {
Route
} from 'react-router-dom';
import Dashboard from "./content/Dashboard";
import Utenti from "./content/Utenti";
const navRoutes = (
<div>
<Route path="/dashboard" component= {Dashboard}/>
<Route path="/utenti" component = {Utenti} />
<Route path="/corsi" component = {Corsi} />
</div>
);
export default navRoutes;
Now everything works fine and the page changes when you click on the sidebar links!