Good morning community StackOverflow.I had to use the route to access some component inside the application but that's not work for me despite I had installed the "npm install react-router-dom" the browser render me a blank file,so this is all my file :
app.js file :
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My Shop</a>
</div>
<div>
Cart
Sign In
</div>
</header >
<main>
<Route path="/" component={HomeScreen} ></Route>
<Route path="/product/:id" component={ProductScreen} ></Route>
</main>
<footer classNameName="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
this is the HomeScreen file :
import React from "react";
import {data} from '../data';
import Product from '../components/Product';
function HomeScreen () {
return (
<div>
<div className="row center">
{data.products.map((product) => (
<Product key={product._id} product={product} ></Product>
))}
</div>
</div>
)
};
export default HomeScreen;
this is the ProductScreen file :
import React from "react";
function ProductScreen () {
return (
<div>Product Screen</div>
)
};
export default ProductScreen;
this is the Product file code:
import React from 'react';
import Rating from './Rating';
function Product (props) {
const {product} = props;
return (
<div className="card">
<a href="product.html">
<img className="medium" src={product.image} alt={product.name} />
</a>
<div className="card-body">
<a href="product.html">
<h2>{product.name}</h2>
</a>
<Rating rating={product.rating} numReviews={product.numReviews} ></Rating>
<div className="price" >${product.price}</div>
</div>
</div>
)
}
export default Product;
In react router v6, lots of keywords have changed. In addition, various functions like useHistory have also been changed. Check the package version in package.json file. You can also check your browser console for errors.
In case you have v6 or above, change your app.js as below, to make it work. I have changed the react router keywords, indented code and made Route tag as self closing.
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My Shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<Routes>
<Route path="/" element={<HomeScreen />} />
<Route path="/product/:id" element={<ProductScreen />} />
</Routes>
</main>
<footer classNameName="row center" >All right reserved</footer>
</div>
</Router>
);
}
export default App;
If you're using version 6, you have to wrap <Route> components with <Routes> (you should import the component first), otherwise, wrap them with <Switch> component
Related
I have downloaded everything and it is not showing or displaying anything on the page. Here is the error that is showing in the inspect
Here is the code
This is App.js
//import logo from './logo.svg';
import './App.css';
import { BrowserRouter , Routes, Route } from 'react-router-dom';
import HomeScreen from './screens/HomeScreen';
function App() {
return (
<BrowserRouter>
<div>
<header>
VAC
</header>
<main>
<Routes>
<Route path="/" element={<HomeScreen/>}/>
</Routes>
</main>
</div>
</BrowserRouter>
);
}
export default App;
This is HomeScreen.js
import data from '../data';
function HomeScreen() {
return (
<div>
<h1>Features Products </h1>
<div className="products">
{data.products.map((product) => (
<div className="product" key={product.slug}>
<a href={`/product/${product.slug}`}>
<img src={product.image} alt={product.name} />
</a>
<div className="product-info">
<a href={`/product/${product.slug}`}>
<p>{product.name}</p>
</a>
<p>
<strong>${product.price}</strong>
</p>
<button> Add To Cart</button>
</div>
</div>
))}
</div>
</div>
);
}
export default HomeScreen;
where can be the mistake? please help me
Let's try to break your App a bit, so it will be clearer what happens.
Layout that is same for all routes should be provided in toplevel route, not around Routes. Outlet inside Layout component will be replaced with particular route.
For more about Outlet check official documentation, I warmly recommend this tutorial.
import './App.css';
import { BrowserRouter , Routes, Route } from 'react-router-dom';
import HomeScreen from './screens/HomeScreen';
function Layout() {
return (
<div>
<header>
VAC
</header>
<main>
<Outlet />
</main>
</div>
);
}
function App() {
return (
<Routes>
{/* Here we provide styles through Layout component. */}
<Route path="/" element={<Layout />}>
<Route index element={<HomeScreen />} />
</Route>
</Routes>
);
}
/* It's good idea to separate providers from App. */
function WrappedApp() {
return (
<BrowserRouter>
<App />
</BrowserRouter>
);
}
export default WrappedApp;
If still nothing is displayed, please right click on webpage and in menu choose "inspect page source" and please provide what it shows. Additionaly it would also be useful to see index.ts file.
import { BrowserRouter as Router } from "react-router-dom";
import { render } from "react-dom";
import App from "./components/App";
render(
<Router>
<App />
</Router>,
document.getElementById("app")
);
// App.js
import React from "react";
import { Route, Switch } from "react-router-dom";
import HomePage from "./home/HomePage";
import AboutPage from "./about/AboutPage";
import Header from "./common/Header";
import PageNotFound from "./PageNotFound";
function App() {
return (
<div className="container-fluid">
<Header />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route component={PageNotFound} />
</Switch>
</div>
);
}
export default App;
<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>
This is my first reactjs application and I have an issue with the navigation. When I try to navigate via url .../posts or ../home only the main App page is showing up. How can I fix this? Thank you in advance!
I have App main page where user can Login or Register:
import React,{useState, useEffect} from 'react';
import {Register} from './subcomponents/Register';
import {Login} from './subcomponents/Login';
export function App() {
return (
<div className="root">
<Login />
<p>Hi {name}</p>
<Register/>
</div>
);
}
Home page, when the user is logged in to be redirected:
import React from 'react';
import { Posts } from './Posts';
import {Home} from './Home.jsx';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import {Nav} from './Nav';
export function Home(){
return(
<div id="home">
<BrowserRouter>
<Nav/>
<Routes>
<Route path='/home' element={<Home/>}/>
<Route path="/posts" element={<Posts/>}/>
</Routes>
</BrowserRouter>
<h3>This is the home page</h3>
</div>
)
}
Nav component:
import React from 'react';
import {Link} from 'react-router-dom'
import '../css/nav.css';
import Logo from '../images/Logo.png';
export function Nav(){
return(
<div id="nav">
<img src={Logo} className="nav-logo" alt="logo"/>
<ul>
<li>
<Link to="/home">Home</Link>
</li>
<li>
<Link to="/posts">Posts</Link>
</li>
</ul>
</div>
)
}
for access to components in the project by url,it need be to render before.
export function App(){
return(
<BrowserRouter>
<div id="app">
<Routes>
<Route path='/home' element={<Home/>}/>
<Route path="/posts" element={<Posts/>}/>
</Routes>
</div>
</BrowserRouter>
)
}
import {BrowserRouter , Route} from 'react-router-dom';
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
function App() {
return (
<BrowserRouter>
<div className="grid-container">
<header className="row">
<div>
<a className="brand" href="index.html">SanaMall.</a>
</div>
<div>
<a className="link" href="/cart"> Cart</a>
<a className="link" href="/signin"> Sign In</a>
</div>
</header>
<main>
<Route path= "/" component={HomeScreen}/>
<Route path="/product/:id" component={ProductScreen}/>
</main>
<footer className="row center">
All rights reserved.
</footer>
</div>
</BrowserRouter>
);
}
export default App;
So my problem is that when i put exact path on the component HomeScreen, it doesnt render anything and then the ProductScreen only appears on the browser. Then if the HomeScreen shows in the brower, whenever i clicked on a product, it only refreshes the HomeScreen and it doesn't show the ProductScreen.
Hope you guys could help me. This have been my problem for almost 3 days.
If this code can't work let me know
import {BrowserRouter ,Switch, Route} from 'react-router-dom';
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
function App() {
return (
<BrowserRouter>
<div className="grid-container">
<header className="row">
<div>
<a className="brand" href="index.html">SanaMall.</a>
</div>
<div>
<a className="link" href="/cart"> Cart</a>
<a className="link" href="/signin"> Sign In</a>
</div>
</header>
<Switch>
<Route exact path="/" >
<HomeScreen />
</Route>
<Route path="/product/:id">
<ProductScreen />
</Route>
</Switch>
<footer className="row center">
All rights reserved.
</footer>
</div>
</BrowserRouter>
);
}
export default App;
Use Switch to exclusively render each route https://reactrouter.com/core/api/Switch
I have this program where Product.js just showing a list of items with an addToCart button. In the Cart.js, I am trying to show just the items I selected. Following are the files:
App.js
import './App.css';
import React,{useState} from 'react';
import {
Route,
BrowserRouter as Router,
Switch,
} from 'react-router-dom';
import Cart from './components/Cart';
import Product from './components/Product';
import {ProductProvider} from './ItemListContext';
function App() {
const [cart, setCart]= useState([]);
const addToCart=(product)=>{
setCart([...cart, {...product}])
}
console.log(cart)
return (
<div className="App">
<ProductProvider>
<Router>
<Switch>
<Route path="/" exact
render ={()=> < Product addToCart={addToCart}/>}
/>
<Route path="/cart/" exact
render ={()=> < Cart cart = {cart} />}
/>
</Switch>
</Router>
</ProductProvider>
</div>
);
}
export default App;
Product.js
import React,{useContext, useState} from 'react';
import {ProductContext} from '../ItemListContext';
export default function Product({addToCart}) {
const [products, setProducts] = useContext(ProductContext)
return(
<div className="main-page">
products
<h1>Product Page </h1>
<div className="products" >
{products.map((product, idx)=>(
<div key={idx}>
<h3>{product.name} </h3>
<img src= {product.image} /> cost = {product.cost}
<button onClick={()=>addToCart(product)}
>Add to Cart</button>
</div>
))}
</div>
<div>
</div>
</div>
)
}
ItemListContext.js
import React,{createContext, useState} from 'react';
export const ProductContext = createContext();
export function ProductProvider(props) {
const [products, setProducts]=useState([
{
name: 'iPhone',
cost : '$899.99',
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQB6BMWrPXA9KyTtxa6o600mjeUNJ7zSXgaNt--FDCR6YjQ4XWS5G1J3dSF5ChurfQEGxorkxYs&usqp=CAc',
},
{
name: 'Samsung',
cost : '$599.99',
image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQUGMCcF3_XBIKH5Dja-9iCkRP4CSA-CYaylQ&usqp=CAU'
}
])
return (
<div>
<ProductContext.Provider value={[products, setProducts]} >
{props.children}
</ProductContext.Provider>
</div>
)
}
Cart.jsx
import React from 'react';
export default function Cart({cart}) {
console.log()
return (
<div className="cart">
<h1>cart {cart.length}</h1>
<div className="products" >
{cart.map((product, idx)=>(
<div key={idx}>
<h3>{product.name}</h3>
<h4>{product.cost}</h4>
<img src={product.image} alt = {product.name} />
</div>
))}
</div>
<div>
</div>
</div>
)
}
I am trying to create the router link, localhost:3000/ is showing the product list, but localhost:3000/cart/ doesn't show the cart items.
However, if I remove the Routers and run the program like this:
App.js
import './App.css';
import React,{useState} from 'react';
import {
Route,
BrowserRouter as Router,
Switch,
} from 'react-router-dom';
import Cart from './components/Cart';
import Product from './components/Product';
import {ProductProvider} from './ItemListContext';
function App() {
const [cart, setCart]= useState([]);
const addToCart=(product)=>{
setCart([...cart, {...product}])
}
console.log(cart)
return (
<div className="App">
<ProductProvider>
< Product addToCart={addToCart}/>
<Cart cart={cart} />
</ProductProvider>
</div>
);
}
export default App;
the program works just fine.
So my question is, am I doing my Routing the right way? Is this the right way to pass the cart prop?
There are no problem with Routing, you can add the Link above that and it works as expected https://codesandbox.io/s/solitary-river-hvv2q
...
<ProductProvider>
<Router>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/cart">Cart</Link>
</li>
</ul>
<Switch>
<Route path="/" exact>
<Product addToCart={addToCart} />
</Route>
<Route path="/cart/" exact>
<Cart cart={cart} />
</Route>
</Switch>
</Router>
</ProductProvider>
...
When you directly navigate to /cart by typing that link on browser, your App is re-render then cart is set to empty array, you should store it in storage to prevent that issue.
Considering this React function:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom'
import HomeScreen from './Screens/HomeScreen'
import './App.css';
import currentStrings from './utils/currentlang'
function App() {
const currentlang = currentStrings;
const switchLanguage = () =>{
console.log("switching...");
currentlang.switchLang();
}
return (
<BrowserRouter>
<div className="grid-container">
<header className="header">
<div className="brand">
<Link to="/" >
</Link>
</div>
<div className="header-side">
{currentlang.getCurrent.subtitle}
</div>
<div className="header-right">
<button onClick={switchLanguage}> {currentlang.getCurrent.traduction} </button>
</div>
<div>
</div>
</header>
<main className="main">
<div className="content">
<Route path="/" exact={true} component={HomeScreen} />
</div>
</main>
<footer className="footer">
© 2020
</footer>
</div>
</BrowserRouter>
);
}
export default App;
i want to switch the language when i click on the button, the function itself changes a variable that contains the list of html text. However, all the research has given me solutions by using classes to change the state of my page, but my project is functional and doesn't work in my context.