I have a problem with my proxy. When I am in the homepage, the proxy is working but when I go to another page (using Link from react-router-dom) it's not taken into account.
I have the error: Object { message: "Request failed with status code 404", name: "AxiosError", code: "ERR_BAD_REQUEST"..}
and the http request is : http://localhost:3000/profile/posts/profile/olive
but I want it to be : http://localhost:8800/api/profile/olive
In package.json I have : "proxy": "http://localhost:8800/api/"
And here are the scripts that I use (Feed.jsx):
import "./feed.css";
import Share from "../share/Share";
import Post from "../post/Post";
import { useState, useEffect } from "react";
import axios from "axios"
export default function Feed({ username }) {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
const res = username
? await axios.get("posts/profile/" + username)
: await axios.get("posts/timeline/629f61ef4ed27a5d39094ced");
setPosts(res.data)
};
fetchPosts();
}, []);
return (
<div className="feed">
<div className="feedWrapper">
<Share />
{posts.map((p) => (
<Post key={p._id} post={p} />
))}
</div>
</div>
)}
This is my App.js:
import {
BrowserRouter as Router,
Routes as Switch,
Route,
} from "react-router-dom";
import Homepage from "./pages/homepage/Homepage";
import Login from "./pages/login/Login"
import Register from "./pages/register/Register"
import Profile from "./pages/profile/Profile"
function App() {
return (
<>
<Router>
<Switch>
<Route exact path="/" element={<Homepage/> }/>
<Route exact path="/login" element={<Login/> }/>
<Route exact path="/register" element={<Register/> }/>
<Route path="/profile/:username" element={<Profile/> }/>
</Switch>
</Router>
</>
);
}
export default App;
This is my Profile.jsx:
import "./profile.css"
import Topbar from "../../components/topbar/Topbar";
import Sidebar from "../../components/sidebar/Sidebar";
import Feed from "../../components/feed/Feed";
import Rightbar from "../../components/rightbar/Rightbar";
export default function Profile() {
const PF=process.env.REACT_APP_PUBLIC_FOLDER;
return(
<>
<Topbar/>
<div className="profile">
<Sidebar/>
<div className="profileRight">
<div className="profileRightTop">
<div className="profileCover">
<img src={`${PF}post/3.jpeg`} alt="" className="profileCoverImage" />
<img src={`${PF}person/5.jpeg`} alt="" className="profileUserImage" />
</div>
<div className="profileInfo">
<h4 className="profileInfoName">Louise Dupuis</h4>
<span className="profileInfoDesc">Hello everyone I am a spiritual coach</span>
</div>
</div>
<div className="profileRightBottom">
<Feed username="olive"/>
<Rightbar profile/>
</div>
</div>
</div>
</>
);
}
And this is how I linked a button from the homepage to the profile page.
<Link to={`/profile/${user.username}`}>
<img className="postProfileImage" src={user.profilePicture || PF+"person/no_avatar.png"} alt="" />
</Link>
Thank you in advance for your attention and your help. I really tried and searched but I didn't find. I don't know what's wrong in my code ...
Related
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom';
import './Allproducts.css'
import Categories from './categories.json'
import ForYouItem from './ForYouItem'
export default function Allproducts(props) {
const [products, setProducts] = useState([]);
useEffect(() => {
fetch(`https://fakestoreapi.com/products/category/${props.category}`)
.then((res) => res.json())
.then((data) => setProducts(data))
}, [])
return (
<>
<div className="banner">
<h1>All Products</h1>
<h4>Get best items in budget</h4>
</div>
<div className="main-grid">
<div className="left-grid">
<div className="left-categories">
<h1>Collections</h1>
{Categories.map((category) => {
let Afeef = `/${props.category}`
return (
<Link to= {Afeef} className='products-categories'> <h4>{category.title}</h4></Link>
)
}
)}
</div>
</div>
<div className="right-grid">
<div className="row ">
{products.map((product) => {
return (
<div className="col-md-4 my-2 Products-1">
<ForYouItem Title={product.title.slice(0, 50)} Price={product.price} Imageurl={product.image} rate={product.rating.rate} count={product.rating.count} />
</div>
)
}
)}
</div>
</div>
</div>
</>
)
}
So in this code I am calling same prop two times, first in this line;
fetch(https://fakestoreapi.com/products/category/${props.category})
Secondly here;
let Afeef = /${props.category}
The prop is working in the First line but on the second line it gives no result. The link isn't changed.
What I want is when I click on second Link I get redirected "/${props.category}" but the URL is not changing
Code for App.js:
import React, { Component } from 'react'
import './App.css';
import NavBar from './components/NavBar';
import TopBar from './components/TopBar'
import {
HashRouter,
Routes,
Route,
} from "react-router-dom";
import Mainpage from './Mainpage';
import Login from './components/Login';
import Signup from './components/Signup';
import Allproducts from './components/Allproducts';
function App() {
return (
<div>
<HashRouter>
<TopBar/>
<NavBar/>
<Routes>
<Route path="/" element={<Mainpage/>}></Route>
<Route path="/Login" element={<Login/>}></Route>
<Route path="/Signup" element={<Signup/>}></Route>
<Route path="/jewelery" element={<Allproducts category="jewelery"/>}></Route>
<Route path="/electronics" element={<Allproducts category="electronics"/>}></Route>
<Route path="/men's clothing" element={<Allproducts category="men's clothing"/>}></Route>
<Route path="/women's clothing" element={<Allproducts category="women's clothing"/>}></Route>
</Routes>
</HashRouter>
</div>
);
}
export default App;
I'm new to react and I'm trying to build application to make reservation for fishing charters for a school project I'm working on. I'm using react-router-dom which works for the most part, but when I try and use a button to navigate to page it does not render components on 2 of the pages. The page will refresh but it does not render the components "CharterDetails" or "BookCharter".
I get no errors but I do get a warning that says:
No routes matched location "/charterdetails/62fb097cb985e11cb3884f6e"
It does not seem to matter if I use the button handler or just a link both options give the same result for both CharterDetails and BookCharter, navigation for other pages render as expected.
Click here for my GitHub repository
select the work-in-progress branch
hope I’m explaining clear enough. Thank for your time
App.js:
import React, { useState, useEffect } from "react";
import Nav from "./Components/Nav";
import {
BrowserRouter as Router,
Route,
Routes,
useParams,
} from "react-router-dom";
import Login from "./Components/Users/LoginForm";
import "./App.css";
import Landings from "./Pages/Landings.js";
import Boats from "./Pages/Boats";
import Charters from "./Pages/Charters";
import CharterDetails from "./Pages/CharterDetails";
import BookCharter from "./Pages/BookCharter";
import PageNotFound from "./Pages/404";
import Home from "./Pages/Home";
function App() {
const { id } = useParams();
console.log("useParams", id);
return (
<>
<header>
<img
src="../assets/Images/scsfcBadge.png"
alt="SoCal Sportfishing Club"
/>
SoCal Sportfishing Club
</header>
<div className="main">
<Router>
<aside className="left">
<Nav />
</aside>
<main>
<Routes>
<Route index element={<Home />} />
<Route path="/charters" element={<Charters />} />
<Route path="/landings" element={<Landings />} />
<Route path="/boats" element={<Boats />} />
{/* need to add parameter :id to link */}
<Route page="/bookcharter/" element={<BookCharter />} />
{/* need to add parameter :id to link */}
<Route page="/charterdetails/:id" element={<CharterDetails />} />
<Route page="*" element={<PageNotFound />} />
</Routes>
</main>
<aside className="right">
<Login />
</aside>
</Router>
</div>
<footer>Copyright © 2022 SoCal SportFishing Club </footer>
</>
);
}
export default App;
Home.js:
import React,{useState , useEffect} from 'react';
import { Link, useNavigate } from "react-router-dom";
import { BrowserRouter as Router, Route, Routes, useParams } from "react-router-dom";
function Home(){
const navigate = useNavigate();
const [charterData, setCharterData] = useState([]);
const [charterid, setCharterid] = useState('');
useEffect(() => {
// declare the async data fetching function
const fetchData = async () => {
fetch('http://localhost:5000/charter/featured/')
.then((response) => response.json())
.then((data) => setCharterData(data));
console.log('Charter ', charterData)
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);
}, [])
function handleClick(charter) {
let id = charter.id;
let path = `/charterdetails//${id}`
navigate(path);
}
function BookClick(e) {
// e.preventDefault();
let path = `/bookcharter/${e.target.id}`
navigate(path);
}
return(
<div className="container">
{
charterData.map((charter, index) => {
return(<div key={index} className="card">
<div className="card-header">
</div>
<img src={'../assets/Images/charters/' + charter.Img} alt={charter.CharterName} />
<div className="tag tag-teal">{charter.BoatName} - {charter.Duration}</div>
<div className="card-body">
<div style={{fontSize:'28px', fontWeight: 'Bold'}}>
{charter.CharterName}
</div>
<p style={{fontSize:'16px'}}>Departure date: {new Date(charter.Departure).toDateString()}<br />
Return date: {new Date(charter.Return).toDateString()}<br />
Trip Duration: {charter.Duration}<br />
Price: ${charter.Cost}<br />
Max Load:{charter.MaxLoad}<br />
Target: {charter.Target}<br /></p>
<div style={{textAlign:'center', width: '100%'}}>
<Link
to= {{
pathname:`/charterdetails/${charter.id}`
}}
>
<button>Details</button>
</Link>
<button onClick={BookClick}>Book</button>
</div>
</div>
</div>)
})
}
</div>
)
}
export default Home;
Nav.js:
import React from 'react';
import { Link } from "react-router-dom";
export default function Nav() {
return (
<>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/landings">Landings</Link>
</li>
<li>
<Link to="/boats">Boats</Link>
</li>
<li>
<Link to="/charters">Club Charters</Link>
</li>
<li>
<Link to="/charterdetails">Charter Details</Link>
</li>
<li>
<Link to="/bookcharter">Book Charter</Link>
</li>
</ul>
</>
);
}
CharterDetails.js:
import React from 'react';
function CharterDetails(){
return(
<div>
Charter Details
</div>
)
}
export default CharterDetails;
BookCharter.js:
import React from "react";
function BookCharter(){
return(
<>
Book Charter
</>
)
}
export default BookCharter;
In the app.js I had page instead of path on the route.
Changed from
<Route page="/bookcharter" element={<BookCharter />} />
<Route page="/charterdetails/:id" element={<CharterDetails />} />
to
<Route exact path="/bookcharter" element={<BookCharter />} />
<Route exact path="/charterdetails/:id" element={<CharterDetails />} />
Having trouble displaying a list of Github usernames and profile pics.
I'm using https://api.github.com/users to fetch the data from the API. I haven't started working on the profile links yet.
Here's what's being displayed
Here's my App.js:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'
import Home from './pages/Home';
import About from './pages/About';
import NotFound from './pages/NotFound';
import Navbar from './components/layout/Navbar';
import Footer from './components/layout/Footer';
function App() {
return (
<Router>
<div className='flex flex-col justify-between h-screen'>
<Navbar />
<main className='container mx-auto px-3 pb-12'>
<Routes>
<Route path='/' element={< Home />} />
<Route path='/about' element={< About />} />
<Route path='/notfound' element={< NotFound />} />
<Route path='/*' element={< NotFound />} />
</Routes>
</main>
<Footer />
</div>
</Router>
);
}
export default App;
Here's UserResults.jsx:
import {useEffect, useState} from 'react'
import Spinner from '../layout/Spinner'
import UserItem from './UserItem'
function UserResults() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchUsers()
}, [users])
const fetchUsers = async () => {
const response = await fetch(`https://api.github.com/users`)
const data = await response.json()
setUsers(data)
setLoading(false)
}
if (!loading) {
return (
<div className='grid grid-cols-1 gap-8 xl:grid-cols-4
lg:grid-cols-3 md:grid-cols-2'>
{users.map((user) => (
<UserItem key={user.id} user={user} />
))}
</div>
)
} else {
return <h3><Spinner /></h3>
}
}
export default UserResults
UserItem.jsx which displays the user info:
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
function UserItem({users: login, avatar_url}) {
return (
<div className='card shdow-md compact bg-base-100 '>
<div className='flex-row items-center space-x-4 card-body'>
<div>
<div className='avatar'>
<div className='rounded-full shadow w-14 h-14'>
<img src={avatar_url} alt='profile pic'></img>
</div>
</div>
</div>
<div>
<h2 className='card-title'>{login}</h2>
<Link className='text-base-content text-opacity-40' to={`/users/${login}`}>
Visit Profile
</Link>
</div>
</div>
</div>
)
}
UserItem.propTypes = {
users: PropTypes.object.isRequired,
}
export default UserItem
Feel like I'm missing something with the way I reference the API.
Thank you in advance!
The UserItem component is being called as:
<UserItem key={user.id} user={user} />
You should define it as follows:
function UserItem({key, user}) {
// here you can use user.avatar_url and any other user related key
Seems that object destructuring in UserItem function is written wrong:
function UserItem({users: { login, avatar_url }}) {
I'm trying to get idrestaurant for use as identifier from json document that has info like this on json objects on the database. Stuff is on PostgreSQL
This is a react website for a school project. I have tried printing response.data on a console log but nothing shows.
[{"idrestaurant":2,
"name":"Pizzeria Amigo",
"address":"Uusikatu 16",
"opening":"08:00",
"closing":"12:00",
"img":"testi.com/kuva.jpg",
"type":"fastfood",
"pricelvl":"3",
"owneruserid":1},
{"idrestaurant":3,
"name":"Burgers",
"address":"Katu 10",
"opening":"08:00",
"closing":"18:00",
"img":"testi.com/kuva.png",
"type":"fastfood",
"pricelvl":"1",
"owneruserid":1}]
I want to use id as idrestaurant as unique key for printing list of restaurant elements at Restaurant.js. Here is what I have been trying to do.
App.js
import React, { useEffect, useState } from 'react'
import './App.css'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import NavBar from './components/navBar'
import Restaurants from './components/Restaurants'
import searchRestaurant from './components/Search'
import Restaurant from './components/Restaurant'
import axios from 'axios'
const App = () => {
const [restaurants, setRestaurants] = useState([])
useEffect(() => {
axios.get('http://MadeUpURL-app.herokuapp.com/restaurants')
.then((response) => {
setRestaurants(response.data)
});
}, []);
return (
<Router>
<div>
<NavBar />
<Routes>
<Route path='/restaurants' element={<Restaurants restaurants={restaurants} />} >
<Route path="/restaurants/idrestaurant" element={<Restaurant restaurants={restaurants} />} />
</Route>
{/* <Route path='/Search' element={<Search />} /> */}
</Routes>
</div>
</Router>
);
}
export default App
Restaurants.js
import React from 'react'
import styles from './restaurants.module.css'
import Restaurant from './Restaurant'
import { Link } from 'react-router-dom'
const Restaurants = (props) => {
return (
<div className={styles.container}>
<div className={styles.restaurantList}>
{props.restaurants.map(restaurant => <Link to={restaurant.idrestaurant}>
<Restaurant key={restaurant.idrestaurant} />
</Link>
)}
</div>
</div>
)
}
export default Restaurants
Restaurant.js
import React from 'react'
import styles from './restaurant.module.css'
export default function Restaurant(props) {
return (
<div className={styles.shop}>
<div>
<div><img src={props.img} className={styles.imageSize} /></div>
<div>
<div className={styles.title}>{props.name}</div>
<div className={styles.type}>{props.type}</div>
<div className={styles.prange}>{props.pricelvl}</div>
</div>
</div>
</div>
)
}
it is preferable to call api inside the Restaurants Component. Because setRestaurants will take time to update the state and in the mean time Restaurants Component will be render already so restaurants will be null in <Restaurants restaurants={restaurants} />
WORKING DEMO
Here is the code for App.js
import React, { useEffect, useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Restaurants from "./components/Restaurants";
import Restaurant from "./components/Restaurant";
const App = () => {
return (
<Router>
<div>
<Routes>
<Route path="/" element={<Restaurants />} />
<Route path="/restaurants" element={<Restaurants />}>
<Route path="/restaurants/idrestaurant" element={<Restaurant />} />
</Route>
{/* <Route path='/Search' element={<Search />} /> */}
</Routes>
</div>
</Router>
);
};
export default App;
Here is the code for Restaurants.js
import React, { useEffect, useState } from "react";
import Restaurant from "./Restaurant";
import { Link } from "react-router-dom";
import axios from "axios";
const Restaurants = (props) => {
const [restaurants, setRestaurants] = useState([]);
const jsonFakeData = [
{
idrestaurant: 2,
name: "Pizzeria Amigo",
address: "Uusikatu 16",
opening: "08:00",
closing: "12:00",
img: "testi.com/kuva.jpg",
type: "fastfood",
pricelvl: "3",
owneruserid: 1
},
{
idrestaurant: 3,
name: "Burgers",
address: "Katu 10",
opening: "08:00",
closing: "18:00",
img: "testi.com/kuva.png",
type: "fastfood",
pricelvl: "1",
owneruserid: 1
}
];
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/users").then((response) => {
console.log(response.data);
//setRestaurants(response.data);
setRestaurants(jsonFakeData);
});
}, []);
return (
<div>
<div>
{restaurants && restaurants.length > 0
? restaurants.map((restaurant) => (
<Link key={restaurant.idrestaurant} to={restaurant.idrestaurant}>
<Restaurant
restaurant={restaurant}
key={restaurant.idrestaurant}
/>
</Link>
))
: ""}
</div>
</div>
);
};
export default Restaurants;
Here is the code for Restaurant.js
import React from "react";
export default function Restaurant(props) {
console.log(props, "prps");
return (
<div>
<div>
<div>
<img src={props.restaurant.img} alt="img" />
</div>
<div>
<div>{props.restaurant.name}</div>
<div>{props.restaurant.type}</div>
<div>{props.restaurant.pricelvl}</div>
</div>
</div>
</div>
);
}
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.