React Route not adding forward slash with path="/post/:slug" - javascript

For some reason when I click on one of the posts in the collection of posts section to view the info on one single post, my code is not adding a forward slash / in the URL like so : http://localhost:3000/postyou-just-could-not-have where the URL I need is http://localhost:3000/post/you-just-could-not-have.
Is there a way to add a / to the URL or figure out why it is not being generated?
App.js with Route <Route path="/post/:slug" element={<SinglePost />} /> in question :
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import SinglePost from './components/SinglePost';
import Post from './components/Post';
import Project from './components/Project';
import NavBar from './components/NavBar';
function App() {
return (
<Router>
<NavBar />
<Routes>
<Route path="/" element={<Home />} exact />
<Route path="/about" element={<About />} />
<Route path="/post/:slug" element={<SinglePost />} />
<Route path="/post" element={<Post />} />
<Route path="/project" element={<Project />} />
</Routes>
</Router>
);
}
export default App;
SinglePost.js component attempting to build URL from slug value :
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import sanityClient from '../client';
import BlockContent from '#sanity/block-content-to-react';
import imageUrlBuilder from '#sanity/image-url';
const builder = imageUrlBuilder(sanityClient);
function urlFor(source) {
return builder.image(source);
}
export default function SinglePage() {
const [singlePost, setSinglePost] = useState(null);
const { slug } = useParams();
useEffect(() => {
sanityClient
.fetch(
`*[slug.current == "${slug}"]{
title,
_id,
slug,
mainImage{
asset->{
_id,
url
}
},
body,
"name": author->name,
"authorImage": author->image
}`
)
.then((data) => setSinglePost(data[0]))
.catch(console.error);
}, [slug]);
if (!singlePost) {
return <div>Loading...</div>;
}
return (
<main className="bg-gray-200 min-h-screen p-12">
<article className="container shadow-lg mx-auto bg-green-100 rounded-lg">
<header className="relative">
<div className="absolute h-full w-full flex items-center justify-center p-8">
<div className="bg-white bg-opacity-75 rounded p-12">
<h1 className="cursive text-3xl lg:text-6xl mb-4">
{singlePost.title}
</h1>
<div className="flex justify-center text-gray-800">
<img
src={urlFor(singlePost.authorImage).url()}
alt="bob"
className="w-10 h-10 rouded-full"
/>
<p className="cursive flex items-center pl-2 text-2xl">
{singlePost.name}
</p>
</div>
</div>
</div>
<img
src={singlePost.mainImage.asset.url}
alt="gary"
className="w-full object-cover rounded-t"
style={{ height: '400px' }}
/>
</header>
<div className="px-16 lg:px-48 py-12 lg:py-20 prose lg:prose-xl max-w-full">
<BlockContent
blocks={singlePost.body}
projectId="notReally"
dataset="production"
/>
</div>
</article>
</main>
);
}
Adding Post.js :
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import sanityClient from '../client';
export default function Post() {
const [postData, setPost] = useState(null);
useEffect(() => {
sanityClient
.fetch(
`*[_type == "post"]{
title,
slug,
mainImage{
asset->{
_id,
url
},
alt
}
}`
)
.then((data) => setPost(data))
.catch(console.error);
}, []);
//anything wrapped in Link makes it clickable
return (
<main className="bg-green-100 min-h-screen p-12">
<section className="container mx-auto">
<h1 className="text-5xl flex justify-center cursive">Blog Post Page</h1>
<h2 className="text-lg text=gray-600 flex justify-center mb-12">
Welcome Doggies
</h2>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
{postData &&
postData.map((post, index) => (
<article>
<Link to={'/post' + post.slug.current} key={post.slug.current}>
<span
className="block h-64 relative rounded shadow leading-snug bg-white border-l-8 border-green-400"
key={index}
>
<img
src={post.mainImage.asset.url}
alt="photo"
className="w-full h-full rounded-r object-cover absolute"
/>
<span className="block relative h-full flex justify-end items-end pr-4 pb-4">
<h3 className="text-gray-800 text-lg font-blog px-3 py-4 bg-red-700 text-red-100 bg-opacity-75 rounded">
{post.title}
</h3>
</span>
</span>
</Link>
</article>
))}
</div>
</section>
</main>
);
}

Links are relative to the route hierarchy by default, unless given a value begin with /.
More about Link
In <Post />, try one of the following:
<Link to={post.slug.current} key={post.slug.current}>
...
/Link>
Or:
<Link to={'/post/' + post.slug.current} key={post.slug.current}>
...
/Link>
These will hopefully generate the right path as /post/:slug.

Related

Passed-down props rendering undefined on first page load?

I have a site that is rendering cards of music artists then allowing the user to click on a button "View Ticket Activity" on each artist's card, which then allows more information to show up. Styled using Tailwind (the class names) and using react-router-v6.
I defined my artists state to successfully pull all the seeded artists from a rails DB and I output these artists all at once via a component called <ArtistsDisplay /> (which is routed to '/artists', where I pass down artists={artists} from the parent component <App />. In <ArtistsDisplay />, each artist maps out.
I have a separate component called <EachArtistCard /> that is routed (in <App />) to '/artists/:id' and is redirected there by a useNavigate() within <ArtistDisplay />. The problem there is that artist passes down from the parent <ArtistDisplay /> to the child <EachArtistCard /> and thisArtist=undefined on the first pass, which then breaks the map function within <EachArtistCard />. I'm defining it as thisArtist in place of artist within as a just in case to not have conflict name-wise with the const thisArtist = artists.find( (artist) => parseInt(id) === parseInt(artist.id) );
Within <ArtistsDisplay /> is my major issue. I've tried many re-writes (replacing the new component with an in-component modal, reconfiguring routes, etc) but fundamentally I need to understand why I have the thisArtist=undefined rendering issue. I'm not in strictMode (afaik) as I've seen the double-render-in-development posts so it's gotta be my error somewhere in my writing of this app.
ArtistsDisplay.js
function ArtistsDisplay({ artists, user, searchTerm, setSearchTerm }) {
let navigate = useNavigate();
return (
<div class='bg-base-900 py-6 sm:py-8 lg:py-12'>
<div class='form-control'>
<label class='flex input-group input-group-lg'>
<span>SEARCH</span>
<input
type='text'
onChange={(e) => setSearchTerm(e.target.value)}
placeholder='Search for your favorite artists here...just start typing'
class='input input-bordered w-full input-lg text-center'
/>
</label>
</div>
<div>
<div class='mx-auto max-w-screen-xl px-4 md:px-8'>
<div class='mb-10 md:mb-16'>
<h1 class='mb-4 text-center text-6xl font-thin text-primary md:mb-6 lg:text-7xl'>
ARTISTS
</h1>
<p class='mx-auto uppercase text-center max-w-screen-md text-secondary text-gray-500 md:text-lg'></p>
</div>
<div class='grid gap-8 mx-6 sm:grid-cols-2 sm:gap-12 lg:grid-cols-3 '>
{artists
.filter((artist) => {
if (searchTerm === '') {
return artist;
} else if (
artist.name.toLowerCase().includes(searchTerm.toLowerCase())
) {
return artist;
}
})
.map((artist) => (
<div>
<div
key={artist.id}
class='card w-96 max-w-xs bg-neutral text-neutral-content shadow-xl'>
<div class='card-body p-4 m-2 mx-0 items-center text-center'>
<div class='avatar'>
<div class='w-30 rounded'>
<img
src={artist.image}
alt='a small avatar of the musical artist'
/>
</div>
</div>
<h1 class='card-title'>{artist.name}</h1>
<p>{artist.genre.name}</p>
<div class='card-actions justify-end'>
<button
class='btn btn-primary'
onClick={() => navigate(`/artists/${artist.id}`)}>
view ticket activity
</button>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
);
}
export default ArtistsDisplay;
EachArtistCard.js
note: even with the two useEffects below commented out, thisArtist still =undefined
import React from 'react';
import { useParams } from 'react-router-dom';
import { useEffect, useState } from 'react';
import IndividualPost from './IndividualPost';
function EachArtistCard({ posts, setPosts, artists }) {
let { id } = useParams();
const thisArtist = artists.find(
(artist) => parseInt(id) === parseInt(artist.id)
);
//* to set selling & looking
useEffect(() => {
thisArtist.posts.map((each) => {
if (each.for_sale === true) {
setSelling(selling + 1);
} else {
setLooking(looking + 1);
}
});
}, []);
//* to set upcomingShows
useEffect(() => {
thisArtist.concerts.map((each) => setUpcomingShows(upcomingShows + 1));
}, []);
return (
<div>
<div class='bg-base-900 py-6 sm:py-8 lg:py-'>
<div class='mx-auto max-w-screen-xl px-4 md:px-8'>
<div class='mb-10 md:mb-16'>
<h1 class='mb-4 text-center text-6xl font-thin uppercase text-primary md:mb-6 lg:text-7xl'>
{thisArtist.name}
</h1>
</div>
<div class='flex justify-center'>
<div class='card w-96 bg-base-500 bg-neutral text-neutral-content justify-center shadow-2xl'>
<div class='avatar'>
<div class='w-30 rounded'>
<img
src={thisArtist.image}
alt='a small avatar of the music thisArtist'
/>
</div>
</div>
<div class='card-body items-center text-center'>
<h2 class='card-title'>{thisArtist.name}</h2>
<p>
There's {upcomingShows} upcoming concerts listed for{' '}
{thisArtist.name}!
</p>
<div>
<div class='badge badge-primary uppercase'>
{selling} selling
</div>
<div class='badge badge-primary uppercase'>
{looking} looking
</div>
</div>
<div class='card-actions justify-end'>
<button class='btn btn-secondary w-full'>
I have tickets to sell
</button>
<button class='btn btn-secondary w-full'>
I'm Looking For Tickets
</button>
<button class='btn btn-outline btn-black w-full'>
Go Back
</button>
</div>
</div>
</div>
</div>
<h2 class='my-10 text-center text-5xl font-thin uppercase text-primary md:mb-6 lg:text-6xl'>
ALL POSTS
</h2>
</div>
</div>
</div>
);
}
export default EachArtistCard;
App.js
removed a lot of other code not pertaining to the situation here
import '../../src/App.css';
import ArtistsDisplay from './ArtistsDisplay';
import ConcertsDisplay from './ConcertsDisplay';
import VenuesDisplay from './VenuesDisplay';
import GenreDisplay from './GenreDisplay';
import Login from './Login';
import SignUp from './SignUp';
import NotFound from './NotFound';
import Header from './Header';
import { Route, Routes } from 'react-router-dom';
import { useState, useEffect } from 'react';
import UsersPage from './UsersPage';
import EachArtistCard from './EachArtistCard';
function App() {
const [user, setUser] = useState('');
const [sessionInfo, setSessionInfo] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
const [artists, setArtists] = useState([]);
useEffect(() => {
fetch('/artists')
.then((r) => r.json())
.then((info) => setArtists(info));
}, []);
return (
<div>
<Header
user={user}
setUser={setUser}
onLogin={onLogin}
onLogout={onLogout}
loggedIn={loggedIn}
/>
<Routes>
<Route
path='/'
element={
<UsersPage
user={user}
cookies={cookies}
sessionInfo={sessionInfo}
loggedIn={loggedIn}
/>
}
/>
<Route
path='/artists'
element={
<ArtistsDisplay
artists={artists}
genres={genres}
user={user}
posts={posts}
setPosts={setPosts}
searchTerm={searchTerm}
setSearchTerm={setSearchTerm}
showModal={showModal}
setShowModal={setShowModal}
/>
}
/>
<Route
path='/artists/:id'
element={
<EachArtistCard
artists={artists}
concerts={concerts}
posts={posts}
setPosts={setPosts}
user={user}
/>
}
/>
<Route path='*' element={<NotFound />} />
</Routes>
</div>
);
}
export default App;
Will take any steps in the right direction as I'm lost. If more info is needed, please let me know.

Can anyone tell me problem with this code? Navbar is not getting displayed

In console this error is getting displayed:
enter image description here
Everything is fine but navbar is not getting displayed with the error above.
Here is my App.js file
import Navbar from './components/Navbar';
import './App.css';
import AddEmployee from './components/AddEmployee';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import EmployeeList from './components/EmployeeList';
function App() {
return (
<>
<BrowserRouter>
<Navbar/>
<Routes>
<Route index element={<EmployeeList/>}/>
<Route path="/" element={<EmployeeList/>}></Route>
<Route path ="/employeeList" element={<EmployeeList/>}></Route>
<Route path ="/addEmployee" element={<AddEmployee/>}></Route>
</Routes>
</BrowserRouter>
</>
);
}
export default App;
Navbar.js
import React from 'react'
const Navbar = () => {
return (
<div className="bg-gray-800">
<div className='h-16 px-8 flex items-center'>
<p className='text-white font-bold'>Employee Management System </p>
</div>
</div>
)
}
export default Navbar;
AddEmployee.js
import React, {useState} from 'react'
import employeeService from '../services/employeeService';
const AddEmployee = () => {
const [employee, setEmployee] = useState({
id: "",
firstName: "",
lastName: "",
emailId: "",
})
const handleChange = (e) => {
const value = e.target.value;
setEmployee({...employee,[e.target.name] : value});
}
const saveEmployee = e => {
e.preventDefault();
employeeService.saveEmployee(employee).then((response) =>{
console.log(response);
}).catch((err) => {
console.log(err);
})
}
return (
<div className="flex max-w-2xl mx-auto shadow border-b">
<div className="px-8 py-8">
<div className="font-thin text-2xl tracking-wider">
<h1>Add New Employee</h1>
</div>
<div className="justify-center items-center h-14 w-full my-4">
<label className="block text-gray-600 text-sm font-normal" >First Name</label>
<input className="h-10 w-96 border mt-2 px-2 py-2"
type="text"
value = {employee.firstName}
onChange = {(e) => handleChange(e)}
name="firstName"></input>
</div>
<div className="justify-center items-center h-14 w-full my-4">
<label className="block text-gray-600 text-sm font-normal" >Last Name</label>
<input className="h-10 w-96 border mt-2 px-2 py-2"
type="text"
value = {employee.lastName}
onChange = {(e) => handleChange(e)}
name="lastName"></input>
</div>
<div className="justify-center items-center h-14 w-full my-4">
<label className="block text-gray-600 text-sm font-normal" >E-Mail</label>
<input className="h-10 w-96 border mt-2 px-2 py-2"
type="email"
value = {employee.emailId}
onChange = {(e) => handleChange(e)}
name="emailId"></input>
</div>
<div className="justify-center items-center h-14 w-full my-4 space-x-4">
<button
className="rounded text-white font-semibold bg-red-600 px-6 hover:bg-green-500 py-2"
onClick={saveEmployee}>
Save
</button>
<button
className="rounded text-white font-semibold bg-orange-600 px-6 hover:bg-green-500 py-2"
>
Clear
</button>
</div>
</div>
</div>
)
}
export default AddEmployee;
It doesnot contain much but just check if there is any error
EmployeeList.js
import React from 'react'
const EmployeeList = () => {
return (
<div>EmployeeList</div>
)
}
export default EmployeeList;
when i am using addEmployee route navbar is working properly but this error persists even then.
Be sure that BrowserRouter is the first element in the Return
<BrowserRouter>
<>
<Navbar/>
<Routes>
....
</>
</BrowserRouter>

Unable to render a react component on click of a button

I have two components: MainContainer and Cart. In MainContainer, I have a button & when clicked it calls a function addToCart with an id argument, which then has to render the Cart component. I am passing that argument as a prop and then extracting the prop value in the Cart component. Wwhen I click on the button, component is not getting rendered. There are no errors as well.
MainContainer.js
import React, { useState } from "react";
import Cart from "./Cart";
import { data } from "./data";
import { Link } from "react-router-dom";
function MainContainer() {
function addToCart(id) {
return (
<div>
<Cart id={id}></Cart>
</div>
);
}
return (
<div className=" grid grid-cols-6">
{data.map((item) => (
<div
key={item.id}
className=" w-52 h-64 m-6 flex flex-col bg-gray-100 shadow-lg border-gray-200 border p-4 items-center justify-center rounded-lg relative"
>
<Link to="/cart">
{" "}
<i
className="fa-solid fa-cart-plus absolute top-3 right-3 cursor-pointer text-lg"
onClick={() => addToCart(item.id)}
></i>
</Link>
<img className=" w-32 h-32" src={item.image} alt="" />
<div className=" bg-gray-300 w-full p-2 rounded-lg mt-2 text-center">
<p className=" font-semibold text-lg"> {item.name}</p>
<p>$ {item.price}</p>
<p>{item.rating}</p>
</div>
</div>
))}
</div>
);
}
export default MainContainer;
Cart.js
import React from "react";
function Cart(props) {
return (
<div>
<h1>hi {props.id} </h1>
</div>
);
}
export default Cart;
addToCart is a callback, it can't return JSX to be rendered. You can store the id in local component state and then conditionally render the Cart component when the id state is populated.
Example:
function MainContainer() {
const [id, setId] = React.useState(); // <-- initially undefined
function addToCart(id) {
setId(id); // <-- defined
}
return (
<div className=" grid grid-cols-6">
{data.map((item) => (
<div
key={item.id}
className="...."
>
<Link to="/cart">
<i
className="...."
onClick={() => addToCart(item.id)}
/>
</Link>
<img className=" w-32 h-32" src={item.image} alt="" />
<div className="....">
<p className=" font-semibold text-lg"> {item.name}</p>
<p>$ {item.price}</p>
<p>{item.rating}</p>
</div>
</div>
))}
{id && (
<div>
<Cart id={id} /> {/* render Cart if id defined */}
</div>
)}
</div>
);
}

React Router not displaying content from json file

Hello again Stackoverflow members.I have GLS I have more similiar components to GLS concept is the same but styling is not, anyway the thing I want to achieve is this, When I press on the Links which are located in HomeComponent/MainPage I want to display/Render the image class and price of that Component in this case A/GLS Components for some reason it does not want to show the data from json file 'I might be blind'. I would be very grateful if someone could help me.
Gls Component
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function GLS({product}) {
return (
<div>
<div key={product.id} className="m-4 bg-blue-100 rounded-xl p-8 absolute ">
<div>
<Link
to={`/payment/${product.id}`}
className="py-1 px-2 text-black-600 h-10 ml-24 mt-32 bg-white w-
36 rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600"
>
Buy Now
</Link>
<img
alt=""
className="w-screen object-contain"
src={product.image}
></img>
<h1 className=" ml-24 md:text-5xl sm:text-5xl top-8">
{product.class}
</h1>
<h1 className="text-base font-mono ml-24 top-24">
{product.price}
</h1>
</div>
</div>
</div>
);
}
export default GLS;
App Component
import React,{useState, useEffect} from 'react'
import './assets/main.css'
import A from './Models/GLS Model/A'
import GLS from './Models/GLS Model/GLS'
import data from "./Models/data.json";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
return (
<div className='' >
<div >
<Router>
<Switch>
<Route path="gls">
{data.map((product) => (
<GLS key={product.id} product={product} />
))}
</Route>
<Route path="a">
{data.map((product) => (
<A key={product.id} product={product} />
))}
</Route>
<Route path="/payment/:productId">
<Payment />
</Route>
<Route exact path="/">
<Home />
</Route>
</Switch>
</Router>
</div>
</div>
);
}
export default App;
import React from 'react'
import {
Link,
} from "react-router-dom";
import data from "./Models/data.json";
function Home() {
return (
<div className='ml-20'>
<nav className='bg-red-50 max-w-full'>
<ul >
<li>
<Link to='GLS'>GLS-class</Link>
</li>
<li>
<Link to="/A"> A-Class</Link>
</li>
</ul>
</nav>
</div>
)
}
export default Home
Payment Component
import React from "react";
import { useParams } from "react-router-dom";
import data from "./Models/data.json";
const Payment = () => {
const { productId } = useParams();
const filteredData = data.filter((product) => product.id === productId)[0];
return (
<div className="ml-20">
<img alt="" className="w:2/4 object-contain " src={filteredData.image} />
<h2
className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-blue-400 absolute top-
48"
>
{filteredData.class}
</h2>
<h3
className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-green-800
font-mono ml-24 top-64 absolute"
>
{filteredData.price}
</h3>
</div>
);
};
export default Payment;
Json file
[
{
"id": 0,
"class": "A-Class",
"image": "./ModImages/Aclass.jpg",
"price": "It goes around $37,300",
},
{
"id": 1,
"class": "GLS-Class",
"image": "./ModImages/GLSclass.jpg",
"price": "It goes around $47,700"
}
]
change
<Route path="gls">
to
<Route path="/gls">
in App Component
and change
<Link to='GLS'>GLS-class</Link>
to
<Link to='/gls'>GLS-class</Link>
in Home Component
and change
{
"id": 0,
"class": "A-Class",
"image": "./ModImages/Aclass.jpg",
"price": "It goes around $37,300",
},
{
"id": 1,
"class": "GLS-Class",
"image": "./ModImages/GLSclass.jpg",
"price": "It goes around $47,700"
}
]
to
[
{
"id": 0,
"class": "A-Class",
"image": "./ModImages/Aclass.jpg",
"price": "It goes around $37,300"
},
{
"id": 1,
"class": "GLS-Class",
"image": "./ModImages/GLSclass.jpg",
"price": "It goes around $47,700"
}
]
in data json file

Having trouble filtering the data from json

Hello again Stackoverflow members.I have GLS Component I have more similiar components to GLS concept is the same but styling is not, anyway the thing I want to achieve is this, when I press on the Link in GLS/A Component I want to display/Render the image class and price of that Component on the payment page for some reason it is giving me this error 'TypeError: Cannot read property 'image' of undefined'. I would be very grateful if someone could help me.
Gls Component
import React from "react";
import data from "../data.json";
import { Link } from "react-router-dom";
function GLS({product}) {
return (
<div>
<div key={product.id} className="m-4 bg-blue-100 rounded-xl p-8 absolute ">
<div>
<Link
to={`/payment/${product.id}`}
className="py-1 px-2 text-black-600 h-10 ml-24 mt-32 bg-white w-
36 rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600"
>
Buy Now
</Link>
<img
alt=""
className="w-screen object-contain"
src={product.image}
></img>
<h1 className=" ml-24 md:text-5xl sm:text-5xl top-8">
{product.class}
</h1>
<h1 className="text-base font-mono ml-24 top-24">
{product.price}
</h1>
</div>
</div>
</div>
);
}
export default GLS;
App Component
import React,{useState, useEffect} from 'react'
import './assets/main.css'
import A from './Models/GLS Model/A'
import GLS from './Models/GLS Model/GLS'
import data from "./Models/data.json";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
return (
<div className='' >
<div >
<Router>
<Switch>
<Route path="gls">
{data.map((product) => (
<GLS key={product.id} product={product} />
))}
</Route>
<Route path="a">
{data.map((product) => (
<A key={product.id} product={product} />
))}
</Route>
<Route path="/payment/:productId">
<Payment />
</Route>
<Route exact path="/">
<Home />
</Route>
</Switch>
</Router>
</div>
</div>
);
}
export default App;
import React from 'react'
import {
Link,
} from "react-router-dom";
import data from "./Models/data.json";
function Home() {
return (
<div className='ml-20'>
<nav className='bg-red-50 max-w-full'>
<ul >
<li>
<Link to='/gls'>GLS-class</Link>
</li>
<li>
<Link to="/a"> A-Class</Link>
</li>
</ul>
</nav>
</div>
)
}
export default Home
Payment Component
import React from "react";
import { useParams } from "react-router-dom";
import data from "./Models/data.json";
const Payment = () => {
const { productId } = useParams();
const filteredData = data.filter((product) => product.id === productId)[0];
return (
<div className="ml-20">
<img alt="" className="w:2/4 object-contain " src={filteredData.image} />
<h2
className=" ml-24 mlg:ml-6 mlg:mt-2 mlg:static text-5xl mlg:text-2xl text-blue-400 absolute top-
48"
>
{filteredData.class}
</h2>
<h3
className="text-lg mlg:mb-2 mlg:ml-6 mlg:mt-2 mlg:static font-bold text-green-800
font-mono ml-24 top-64 absolute"
>
{filteredData.price}
</h3>
</div>
);
};
export default Payment;
Json file
[
{
"id": 0,
"class": "A-Class",
"image": "./ModImages/Aclass.jpg",
"price": "It goes around $37,300",
},
{
"id": 1,
"class": "GLS-Class",
"image": "./ModImages/GLSclass.jpg",
"price": "It goes around $47,700"
}
]
TypeError: Cannot read property 'image' of undefinedThis is a great error to have because it more or less tells you exactly what's wrong. In basic terms, undefined means that a variable has been declared but has not yet been assigned a value.
function myFunc(product) {
return product.img;
}
var product; //initialized to undefined, must explicitly set type;
console.log(myFunc(product));
Result -> Uncaught TypeError: product is undefined
function myFunc(product) {
return product.img;
};
var product; //undefined
product = {}; //explicitly setting to object
product.img = 'image'; // set a name and value
console.log(myFunc(product));

Categories