React Router not displaying content from json file - javascript

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

Related

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

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.

My react component is not displaying using routes

I have a personal project I'm working on and I have run into a bit of a problem. I have two simple code snippets one for the component and one for handling the route.
import { Routes, Route } from "react-router-dom";
function setPath {
return (
<Routes>
<Route path="/sect/guest" element={<MobileCardsGuest />} />
<Routes/>
)
} ```
the setPath component is called in App.js
component to be displayed
import React from "react";
import eventIcon from "../../assets/img/red-carpet.png";
import mealIcon from "../../assets/img/hamburger.png";
import accIcon from "../../assets/img/accomodation.png";
import "../../assets/css/mobilecards.css";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";
function MobileCardsGuest() {
const notify = ()=>{
return toast.info("Coming Soon")
}
return (
<div className="mobile-card">
<p className="text-center mob-title">
<b style={{ color: "var(--pieme-color)" }}>You are Welcome</b>
</p>
<p className="text-center mob-body">Please choose what you would like</p>
<div class="card bg-light m-card">
<p></p>
<img src={mealIcon} className="iconimg" alt="Meal Icon"/>
<div class="card-body text-center">
<p class="card-text">Meal</p>
</div>
</div>
<div class="card bg-light m-card">
<p></p>
<img src={accIcon} className="iconimg" alt="Acc Icon" />
<div class="card-body text-center">
<p class="card-text">Accomodation</p>
</div>
</Link>
</div>
<div class="card bg-light m-card" onClick={notify}>
<p></p>
<img src={eventIcon} className="iconimg" alt="Event Icon"/>
<div class="card-body text-center">
<p class="card-text">Event</p>
</div>
</div>
</div>
);
}
export default MobileCardsGuest;
the other component
import useNavigate from "react-router-dom"
const navigate= useNavigate();
function Navbar{
return (
<button onClick={() => {navigate("/sect/guest")>
Guest
</button>
)
}
When I run the above and go to the path"/sect/guest"` it doesn't display the component.
If you are using react 18 or latest react-router-dom then your routes structure would be like :
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/cart" element={<Cart />} />
</Routes>
<Router>
Here BrowserRouter and switch will not beused in newer version applications.
You need to import BrowserRouter as well.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import MobileCardsGuest from './path/MobileCardsGuest';
const SetPath = () => {
return (
<BrowserRouter>
<Routes>
<Route exact path='/sect/guest' element={<MobileCardsGuest />} />
</Routes>
... ...
</BrowserRouter>
);
}
export default SetPath;

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));

Rendering specific Content from json

So, Hello My problem is this. I have a C-class Component that is 'maping content' that is located in data.json I will add more content later but, in C class I have a button that is currently pushing me to the Payment page, I want when the button is pressed, that it renders the content(image, price, class) only that content from json into the Payment page where I can style it once again that would be basically it. Thanks in Advance
data.json
[
{
"id":0,
"class":"A-Class",
"Info": "A is the cheapest one ",
"imgA":"./ModImages/Aclass.jpg",
"textA":"fdsd",
"trefuA":"fdsd",
"optionA":"fdsd"
},
{
"id":1,
"imgB":"./ModImages/Bclass.jpg",
"classB":"B-Class",
"priceB":"$46,400",
"textB":"fdsd",
"trefuB":"fdsd",
"optionB":"fdsd"
},
{
"id":2,
"classC":"C-Class",
"imgC":"./ModImages/Cclass.jpg",
"priceC":"$46,400",
"textC":"fdsd",
"trefuC":"fdsd",
"optionc":"fdsd"
}
]
C Class Component
import React from 'react'
import data from './data.json'
import { useHistory } from 'react-router'
function C() {
let history = useHistory();
function handleClick() {
history.push("/payment");
}
return (
<div >
{data.map((postData) =>{
console.log(postData)
return(
<div key=
{postData.id}>
<div className='absolute '>
<button onClick={handleClick}className=' absolute 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</button>
<img className='w-screen object-contain'src={postData.imgC}></img>
<h1 className='absolute ml-24 md:text-5xl sm:text-5xl top-8'>{postData.classC}</h1>
<h1 className='text-base font-mono absolute ml-24 top-24'>{postData.priceC}</h1>
</div>
</div>
)
})
}
</div>
)
}
export default C
App Component
import React,{useState, useEffect} from 'react'
import './assets/main.css'
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Header from './Header'
import Home from './Home'
import A from './Models/A'
import B from './Models/B'
import C from './Models/C'
import Payment from './Payment';
function App() {
return (
<div >
<div >
<Router>
<Header />
<Switch>
<Route path="/payment">
<Payment/>
</Route>
<Route path="/C">
<C/>
</Route>
<Route path="/B">
<B />
</Route>
<Route path="/A">
<A />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
</div>
</div>
);
}
export default App;
Home Component
import React from 'react'
import {
BrowserRouter as Router,
NavLink
} from "react-router-dom";
function Home() {
return (
<div className='ml-20'>
<nav className='bg-red-50 max-w-full'>
<ul >
<li>
<Link to="/A">A-Class</Link>
</li>
<li>
<Link to="/B">B-Class</Link>
</li>
<li>
<Link to="/C">C-Class</Link>
</li>
</ul>
</nav>
</div>
)
}
export default Home
You should probably change your route to one with a parameter
<Route path="/payment/:dataId" component={Payment}></Route>
and convert the button to a Link which also passes the id
<Link
to={`/payment/${postData.id}`}
and in the Payment component
also include access to the data.json
get the url parameter from the props
use the provided parameter to find the relevant item in the data
Something like this: https://codesandbox.io/s/festive-spence-bw18s?file=/src/App.js
You can pass additional data with history.push and get it from props in Payment page.
In your C component:
import React from 'react'
import data from './data.json'
import { useHistory } from 'react-router'
function C() {
let history = useHistory();
function handleClick(postData) {
// Pass additional data to Payment component when changing route.
history.push({
pathname: '/payment',
state: {
price: postData.price,
image: postData.image,
class: postData.class
}
});
}
return (
<div >
{data.map((postData) => {
console.log(postData)
return (
<div key=
{postData.id}>
<div className='absolute '>
{/** pass postData to handleClick function */}
<button onClick={() => handleClick(postData)} className=' absolute 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</button>
<img className='w-screen object-contain' src={postData.imgC}></img>
<h1 className='absolute ml-24 md:text-5xl sm:text-5xl top-8'>{postData.classC}</h1>
<h1 className='text-base font-mono absolute ml-24 top-24'>{postData.priceC}</h1>
</div>
</div>
)
})
}
</div>
)
}
export default C
Inside your Payment component you can pull the price, image and class out this way:
import React from 'react';
import { useLocation } from "react-router-dom";
const Payment = () => {
// ...
const location = useLocation();
console.log(location.state.image) // image url from C
console.log(location.state.class) // class from C
console.log(location.state.price) // price from C
// ...
}
export default Payment;

React Hook called in function

i am newbi to react js i was trying to learn by doing project , i was building basic ecom ui with items
i was trying to create a basket to add the item into the cart , but i faced that problem
React Hook "useStateValue" is called in function "product" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooksmponent or a custom React Hook function
import React from 'react';
import "./Product.css"
import { useStateValue } from "./StateProvider";
function product({id,title,image,price,rating}) {
const [{basket},dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item:{
id:id,
title:title,
image:image,
price:price,
rating:rating
},
})
};
return (
<div className="product">
<div className="product__info" >
<p>{title}</p>
<p className="product__price">
<small>$</small>
<strong> {price} </strong>
</p>
<div className="product__rating">
{Array(rating)
.fill( )
.map((_) => (
<p>-</p>
))}
</div>
</div>
<img src={image} alt=""/>
<button onClick={addToBasket} className="product__button"> Add to basket </button>
</div>
);
}
export default product
................................
import React from 'react';
import "./Product.css"
import { useStateValue } from "./StateProvider";
function product({id,title,image,price,rating})
{
const [{basket},dispatch] = useStateValue();
const addToBasket = () => {
dispatch({
type: "ADD_TO_BASKET",
item:{
id:id,
title:title,
image:image,
price:price,
rating:rating
},
})
};
return (
<div className="product">
<div className="product__info" >
<p>{title}</p>
<p className="product__price">
<small>$</small>
<strong> {price} </strong>
</p>
<div className="product__rating">
{Array(rating)
.fill( )
.map((_) => (
<p>-</p>
))}
</div>
</div>
<img src={image} alt=""/>
<button onClick={addToBasket} className="product__button"> Add to basket </button>
</div>
);
}
export default product
.....................................
import React from 'react';
import Product from "./Product";
import "./Home.css";
function Home() {
return (
<div className="home">
<img class="home__image" src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse4.mm.bing.net%2Fth%3Fid%3DOIP.3U6xnN8wOOQ5atG6MO907wHaEK%26pid%3DApi&f=1"/>
<div className="home__row">
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://i.pinimg.com/originals/e6/13/0e/e6130ed7d4820b7eba0a1ba7a631abea.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://i.pinimg.com/736x/ef/c4/01/efc4017b4340dfc35a98ca2235189759.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.byrdie.com%2Fthmb%2F6a2mRHTbEwSWrTOTG1yT5gFDxFs%3D%2F700x700%2Ffilters%3Ano_upscale()%3Amax_bytes(150000)%3Astrip_icc()%2Fcdn.cliqueinc.com__cache__posts__269825__iherb-natural-beauty-products-269825-1539195561186-product.700x0c-6534d2dd4ba1409b84d89684001853df.jpg&f=1&nofb=1"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://s3.images-iherb.com/sre/sre01007/r/1.jpg"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fi.pinimg.com%2Foriginals%2Fb7%2Fb4%2F72%2Fb7b47228df40d8a2759f30aa778ff31c.jpg&f=1&nofb=1"
alt="" />
<Product
id="300"
title="Argan oil"
price={11.96}
rating={5}
image="https://s3.images-iherb.com/now/now04920/r/9.jpg"
alt="" />
</div>
</div>
)
}
export default Home;
I changed two things and error fixed
first in Product.js I changed name of function to Product(capitialzing)
second in reducer.js I changed ...action.item to action.item
1.change the function product to Product in component Product.js that is all and it should work.
its a very simple fix, so the issue is the useStateValue() must start with a capital letter. change it to "UseStateValue()" in the stateProvider.js file and then run it. the compiler will let you know where you have to make the changes and run it. it will solve it
I assume that you're using Context API and creating amazon clone from clever programmer youtube channel.
This error comes when <Home /> component not placed inside <StateProvider> component
Here is my StateProvider.js
import React, { useContext, createContext, useReducer } from 'react';
export const StateContext = createContext();
function StateProvider({ reducer, initialState, children}) {
return (
<StateContext.Provider value={ useReducer(reducer, initialState) }>
{ children }
</StateContext.Provider>
);
}
export const useStateValue = () => useContext(StateContext);
export default StateProvider;
App.js
import React from "react";
import Header from "./components/Header/Header";
import Home from "./components/Home/Home";
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
return (
<StateProvider reducer={Reducer} initialState={initialState} >
<div className="app">
<BrowserRouter>
<Routes>
<Route path="/" element={
<>
<Header />
<Home />
</>
} />
</Routes>
</BrowserRouter>
</div>
</StateProvider>
);
}
export default App;
So kindly check whether the <Home /> component is children of <StateProvider>. Only the child component of StateProvider can access useStateValue() hook.

Categories