I'm having some trouble wherein adding a route path to my app, it gives me a blank page on my HomeScreen. I add this line below to my app.js
<Route path="/" element={HomeScreen} exact />
Can you guys help?
App.js
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 path="/" element={HomeScreen} exact />
</Container>
</main>
<Footer />
</Router>
);
};
export default App;
HomeScreen.js
import { Row, Col } from "react-bootstrap";
import Product from "../components/Product";
import products from "../products";
const HomeScreen = () => {
return (
<>
<h1>Latest Photocards</h1>
<Row>
{products.map((product) => (
<Col key={product._id} sm={12} md={6} lg={4} xl={3}>
<Product product={product} />
</Col>
))}
</Row>
</>
);
};
export default HomeScreen;
Wrap Everything between the BrowserRouter tag
<BrowserRouter>
--here--
<BrowserRouter/>
You have to pass JSX element in your Route as:
<Route path="/" element={<HomeScreen />} exact />
Always wrap all your routes within the BrowserRouter and the Routes Components.
Also the JSX element itself must be passed in to your routes.
Please find the modified snippet below.
<Router>
<Header />
<main className="py-3">
<Container>
<Routes>
<Route path="/" element={<HomeScreen />} exact />
<Routes>
</Container>
</main>
<Footer />
</Router>
Here how i use react-router-dom
index.js
import App from './App';
import { BrowserRouter } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider>
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
</Provider>
);
App.js
import { Route, Routes } from 'react-router-dom';
function App(){
<>
<NavBar />
<Routes>
<Route path="/">
<Route index={true} element={<Home />} />
</Route>
</Routes>
</>
}
Hope this will solve your issue
Related
When a user click on login button it will go to Login page
Like this
I am creating this website for my portfolio But i am facing an error here is my Login and loginwtihgoogle component
Login component
import React from 'react'
const Login = () => {
return (
<>
<div className='login-icon hover:text-yellow-800'>
<a href='Loginwithgoogle'>
<img src="/src/assets/login.png" alt="login icon" className='mt-2 ml-14 h-8 '/>
<figcaption className='text-white text-center ml-14 text-[9px] hover:text-yellow-800'>LOGIN</figcaption>
</a>
</div>
</>
)
}
export default Login
Here is loginwithgoogle component
import React from 'react'
import { useEffect } from 'react'
const Loginwithgoogle = () => {
function handleCallBackResponse(response){
console.log("Encoded JWT ID Token " + response.credential);
}
useEffect(() => {
google.accounts.id.initialize({
client_id: "731249793019-qbik3a0k62db0d3k5vd72j98ivkl2hds.apps.googleusercontent.com",
callback: handleCallBackResponse
});
google.accounts.id.renderButton(
document.getElementById("signInDiv"),
{ theme: "outline", size:"large"}
)
}, [])
return (
<div className="loginwithgoogle">
<div id="signInDiv">
</div>
</div>
)
}
export default Loginwithgoogle
Here it is main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import Bar from './components/Bar'
import IconsText from './components/IconsText'
import Searchbar from './components/Searchbar'
import './index.css'
import {BrowserRouter as Router, Routes,Route} from 'react-router-dom'
import Login from './components/Login'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Router>
<Routes>
<Route path='/loginwithgoogle' element={<Login/>} />
</Routes>
</Router>
<Bar />
<IconsText />
<Searchbar/>
</React.StrictMode>
)
I need to solve this issue when someone clicked on login it should redirect to loginwthgoogle page
You can render the Bar, IconsText, and Searchbar components on their own route.
ReactDOM.createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<Router>
<Routes>
<Route
path="/"
element={(
<>
<Bar />
<IconsText />
<Searchbar />
</>
)}
/>
<Route path='/loginwithgoogle' element={<Login />} />
</Routes>
</Router>
</React.StrictMode>
);
If you want to render these components conditionally with other routes then create a layout route component.
Example:
import { Outlet } from 'react-router-dom';
const Layout = () => (
<>
<Bar />
<IconsText />
<Searchbar />
<Outlet />
</>
);
ReactDOM.createRoot(document.getElementById('root'))
.render(
<React.StrictMode>
<Router>
<Routes>
<Route element={<Layout />}>
... routes with layout ...
</Route>
... routes without layout ...
<Route path='/loginwithgoogle' element={<Login />} />
</Routes>
</Router>
</React.StrictMode>
);
I'm in the very first step to create an project, but the react-router-dom's 'Route' just don't work. When i try to use it, just erase all other things in the screen.
My app.js:
import { BrowserRouter, Route } from 'react-router-dom';
import './App.css';
import Header from './components/Header';
import CoinPage from './Pages/CoinPage';
import Homepage from './Pages/Homepage';
function App() {
return (
<BrowserRouter>
<div>
<Header />
<Route path="/" component={Homepage} />
<Route path="/coins/:id" component={CoinPage} />
</div>
</BrowserRouter>
);
}
export default App;
My CoinPage.js:
import React from 'react'
const CoinPage = () => {
return (
<div>
Coin Page
</div>
)
}
export default CoinPage
My Homepage.js:
import React from 'react'
export const Homepage = () => {
return (
<div>
Homepage
</div>
)
}
export default Homepage
My Header.js:
import React from 'react'
/*The header it self:*/
export const Header = () => {
return (
<div>
Header
</div>
)
}
export default Header
When I remove <Route path="/" component={Homepage}/> and <Route path="/coins/:id" component={CoinPage} /> the 'Header' component appears again
You need to wrap all your Route inside Routes Component
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
<BrowserRouter>
<div>
<Header />
<Routes>
<Route path="/" component={Homepage} />
<Route path="/coins/:id" component={CoinPage} />
</Routes>
</div>
</BrowserRouter>
If you are using v6, then component has been replaced by element in Route
<Route path="/" element={<Homepage />} />
<Route path="/coins/:id" element={<CoinPage />} />
Solved!
I needed to change component to element and put each Route in a different Routes tag. Like that:
<BrowserRouter>
<div>
<Header />
<Routes>
<Route path="/" element={<Homepage />} />
</Routes>
<Routes>
<Route path="/coins/:id" element={<Coinpage />} />
</Routes>
</div>
</BrowserRouter>
i am trying to render different components by clicking on a link but the problem is the url updates and the ui remains same unchanged, everytime i click on different item to render but the same thing happens, i tried a lot to fix it but i can not find a solution for this.
starting from index.js as entry point
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import store from "./Components/store";
import { Provider } from "react-redux";
import "./index.css";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
</StrictMode>,
rootElement
);
then App.js to render components
import "./App.css";
import { Routes, Route } from "react-router-dom";
import { SingleTodoPage } from "./Components/SingleTodoPage";
import { EditTodo } from "./Components/EditTodo";
import { Home } from "./Components/Home";
function App() {
return (
<Routes>
<div>
<div className="header-text">Todo List</div>
<div className="box">
<Route path="/" element={<Home />} />
<Route path="todo/:todoId" element={<SingleTodoPage />} />
<Route path="edit/:todoId" element={<EditTodo />} />
</div>
</div>
</Routes>
);
}
export default App;
SingleTodo where linking different components
<SingleTodo />
<List>
{todos.map((todo) => (
<ListItem key={todo.id} className={classes.listRoot}>
<ListItemText primary={todo.name} />
<ListItemSecondaryAction>
<CheckBoxIcon color="primary" />
<DeleteIcon color="secondary" />
<Link to={`edit/${todo.id}`} className="button">
<EditIcon />
</Link>
<Link to={`todo/${todo.id}`}>view</Link>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
codesandbox for more details, i am using useParams hook in SingleTodo and in EditTodo
to get dynamic url params.
please if anyone knows how to solve this please help me...thanks
Move the non-routing-related elements out of the Routes component.
function App() {
return (
<Routes>
<div>
<div className="header-text">Todo List</div>
<div className="box">
<Route path="/" element={<Home />} />
<Route path="todo/:todoId" element={<SingleTodoPage />} />
<Route path="edit/:todoId" element={<EditTodo />} />
</div>
</div>
</Routes>
);
}
To this
function App() {
return (
<div>
<div className="header-text">Todo List</div>
<div className="box">
<Routes>
<Route path="/" element={<Home />} />
<Route path="todo/:todoId" element={<SingleTodoPage />} />
<Route path="edit/:todoId" element={<EditTodo />} />
</Routes>
</div>
</div>
);
}
The Routes component functions largely as the replacement for react-router-dom v4/5's Switch component.
As I am completely new to React I am trying to wrap my App in Router but I get this error I wrapped it in the div but still not working can someone help me Please ?
Sorry if its irrelevant or stupid question.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import routes from'./routes';
import {Router } from 'react-router-dom';
import history from './history';
import App from './App';
ReactDOM.render(
<Router history={history} routes={routes} >
<div>
<App/>
</div>
</Router>, document.getElementById('root'));
When I use 1 route it works but when i put 2 it doesn't the error is here
import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import AddDetails from './components/AddDetails';
import ShowDetails from'./components/ShowDetails';
import NavBar from "./components/NavBar";
class App extends Component {
render() {
return (
<div >
<NavBar/>
<BrowserRouter>
<Switch>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</Switch>
</BrowserRouter>
</div>
);
}
}
export default App;
This should work:
ReactDOM.render((
<Router history={history} routes={routes} >
<App/>
</Router>),
document.getElementById('root')
);
As per your update, you should wrap your Router with a div or you may use switch:
<BrowserRouter>
<div>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</div>
</BrowserRouter>
Add react router Switch to render only one child component
import {BrowserRouter, Route, Switch} from 'react-router-dom';
<BrowserRouter>
<Switch>
<Route exact={true} path='/' render={() => (
<div>
<AddDetails />
</div>
)}/>
<Route exact={true} path='details' render={() => (
<div>
<ShowDetails />
</div>
)}/>
</div>
</BrowserRouter>
Let me know if the issue still persists
Remove routes prop and pass your routes as child of your div/Switch.
Check the quick start:
https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/quick-start.md
I'm updating my universal react redux app to use react router v4. I have nested routes under a main layout route. Previously I used {props.children} to show contents of child routes, but this doesn't work anymore. How does this work in V4?
<Provider store={store} key="provider">
<div>
<Route component={Layout} />
<Switch>
<Route path="/" component={HomePage} />
<Route component={Error404} />
</Switch>
</div>
</Provider>
or
<Provider store={store} key="provider">
<Layout>
<Route path="/" component={HomePage} />
<Route component={Error404} />
</Layout>
</Provider>
This is how my Layout file looks
const Layout = props => (
<div className="o-container">
<Header />
<main>
{props.children}
</main>
<Footer />
</div>
);
I have taken the <Provider>out because it belongs to react-redux and you don't need it as basis for routing with react-router (anyway you can easily add it encapsulating the structure with it).
In React Router V4, what was Router has been renamed to BrowserRouter and imported from package react-router-dom. So for nesting routes you need to insert this as children of your <Layout>.
index.js
import { Switch, Route } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import Layout from './Layout';
...
const Root = () => (
<Layout>
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/other" component={OtherComponent} />
<Route component={Error404} />
</Switch>
</BrowserRouter>
</Layout>
);
ReactDOM.render(
<Root/>,
document.getElementById('root')
);
Layout.js
import React from 'react';
import Header from './Header';
import Footer from './Footer';
const Layout = props => ({
render() {
return (
<div className="o-container">
<Header />
<main>{props.children}</main>
<Footer />
</div>
);
}
});
export default Layout;
Take in count this only works for web. Native implementation differs.
I uploaded a small project based in Create React App where I show the implementation of nested routes in V4.
Just thought I have to share this. If you're using a Link component in your Header component. The answer above won't work. You would have to make the BrowserRouter as the parent again to support Link. Make it like this:
<BrowserRouter>
<Layout>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/other" component={OtherComponent} />
<Route component={Error404} />
</Switch>
</Layout>
</BrowserRouter>
I would use this structure, without props.children :
const Main = () => (
<main>
<Switch>
<Route exact path="/" component={HomePage} />
<Route component={Error404} />
</Switch>
</main>
)
const Layout = () => (
<div>
<Header />
<Main />
<Footer />
</div>
)
ReactDOM.render((
<Provider store={store}>
<BrowserRouter>
<Layout />
</BrowserRouter>
</Provider>
), document.getElementById('root'))
Please read this blog through. https://codeburst.io/react-router-v4-unofficial-migration-guide-5a370b8905a
No More <IndexRoute>
The component allowed to route to a certain component on a top-level path in v3:
// in src/MyApp.js
const MyApp = () => (
<Router history={history}>
<Route path="/" component={Layout}>
<IndexRoute component={Dashboard} />
<Route path="/foo" component={Foo} />
<Route path="/bar" component={Bar} />
</Route>
</Router>
)
This component doesn’t exist anymore in v4. To replace it, use a combination of , exact, and route ordering (placing the index route last):
// in src/MyApp.js
const MyApp = () => {
<Router history={history}>
<Route path="/" component={Layout} />
</Router>
}
// in src/Layout.js
const Layout = () => (
<div className="body">
<h1 className="title">MyApp</h1>
<div className="content">
<Switch>
<Route exact path="/foo" component={Foo} />
<Route exact path="/bar" component={Bar} />
<Route exact path="/" component={Dashboard} />
</Switch>
</div>
</div>
);
Adding to #Dez answer
Complete native / core implementation with Redux support
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, Switch } from 'react-router';
import createMemoryHistory from 'history/createMemoryHistory';
const history = createMemoryHistory();
import App from './components/App';
import Home from './components/Home';
import Login from './components/Login';
import store from './store';
ReactDOM.render((
<Provider store={ store }>
<Router history={history}>
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/login" component={Login} />
</Switch>
</App>
</Router>
</Provider>
), document.getElementById('root'));
App.js
import Header from './Header';
import Home from './Home';
import React from 'react';
import {connect} from 'react-redux';
const mapStateToProps = state => ({appName: state.appName});
class App extends React.Component {
render() {
return (
<div >
<Header appName={this.props.appName} /> {/*common header*/}
{this.props.children}
</div>
);
}
}
export default connect(mapStateToProps, () => ({}))(App);
If using with Redux, without the Switch element
AppRouter.js
import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
const AppRouter = () => (
<Layout>
<Router>
<div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
</div>
</Router>
</Layout>
)
export default AppRouter;
Layout.js
const Layout = props => ({
render() {
return (
<div className="container">
<Header />
<main>{props.children}</main>
<Footer />
</div>
);
}
});
export default Layout;
Provider placed in Render function
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import AppRouter from './AppRouter';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<AppRouter />
</Provider>
, document.getElementById('app'));