I am having an ecommerce application build in next.js. In this I have top bar contains contact and other link information, below that there is a long and search section. This two items are done in 2 components and both are combined.
Now the problem is, on hover any link in components, the particular page in refreshed (not reloading). What may be the problem. For better understanding I have placed a video blow. Please check.
https://www.dropbox.com/s/tlh4e2os1ok2tpr/screen-recording.webm?dl=0
I have given all link as below,
<Link href="/" as="/">
<a className="mr-4">Help Center</a>
</Link>
Please check my below codes,
Top.js
const Top = () => {
return (
<div>
<div className="topBar">
<div className="container">
<div className="row">
<div className="col-sm-4 col-md-6">
<p className="text-center text-sm-left">
<Link href="/" as="/">
<a>Sell in RangerBee</a>
</Link>
</p>
</div>
<div className="col-sm-8 col-md-6">
<p className="text-center text-sm-right">
<Link href="/" as="/">
<a className="mr-4">Gift Card</a>
</Link>
<Link href="/" as="/">
<a className="mr-4">Help Center</a>
</Link>
<Link href="/" as="/">
<a>Download app</a>
</Link>
</p>
</div>
</div>
</div>
</div>
</div>
}
export default Top;
Header.js
const Header = () => {
return (
<div>
<div className="searchBar">
<div className="container-fluid">
<div className="row align-items-center">
<div className="col-8 col-md-2 col-lg-2">
<p>
<Link href="/" as="/">
<a><img src="/vercel.svg" alt="Example" className="img-fluid" /></a>
</Link>
</p>
</div>
<div className="col-4 col-md-2 col-lg-3 col-xl-2">
<div className="menuCategory">
<p className="main" onClick={() => changeMenuCategory()}><span>Shop By Category</span> <FontAwesomeIcon icon={faChevronDown} className="ml-2 pt-1 fa-down"/> <FontAwesomeIcon icon={faBars} className="ml-2 pt-1 fa-bars"/></p>
<ul className={toggleCategory ? "main-nav" : "main-nav d-none"}>
{menus && menus.data.map((cat, index) => (
<li key={index}>
<Link href={"/products/"+cat.cat_slug} as={"/products/"+cat.cat_slug}><a title={cat.cat_name}>{cat.cat_name} <FontAwesomeIcon icon={faChevronRight} className="ml-2 float-right menu-arrow"/></a></Link>
<ul>
{cat.subcategory.map((subcat, index1) => (
<li key={index1+index}><Link href={"/products/"+cat.cat_slug+"/"+subcat.sub_slug} as={"/products/"+cat.cat_slug+"/"+subcat.sub_slug}><a title={subcat.sub_name}>{subcat.sub_name}</a></Link></li>
))}
</ul>
</li>
))}
</ul>
</div>
</div>
<div className="col-12 col-md-4 col-lg-4 col-xl-5 mt-3 mb-3 mt-md-0 mb-md-0">
<div className="search-box">
<div className="search-inner">
<input type="text" name="q" placeholder="Search for products, brands and much more" onClick={() => setToggleSearch(b => !b)} onFocus={(e) => trendingSearch(e)} onChange={(e) => startSearch(e)} />
<button><FontAwesomeIcon icon={faSearch}/></button>
</div>
<div className={toggleSearch ? "search-result" : "search-result d-none"}>
<ul ref={dropdown}>
{trending !== null && searched === null && trending.data.length > 0 && <li className="trending">Trending Search</li>}
{trending !== null && searched == null && trending.data.length > 0 &&
trending.data.map((trending, index) => (
<li key={index}><Link href={"/products/"+trending.trending_slug} as={"/products/"+trending.trending_slug}><a>{trending.trending_name}</a></Link></li>
))
}
{searched !== null && searched.data.length > 0 &&
searched.data.map((search, index) => (
<li key={index}>
<Link href={search.search_url} as={search.search_url}>
{search.images.length > 0 ?
<a><img src={api.IMAGE_PRODUCTS+"/"+search.images[0].image_name} alt={search.search_name} /> {search.search_name}</a>
:
<a>{search.search_name}</a>
}
</Link>
</li>
))
}
</ul>
</div>
</div>
</div>
<div className="col-12 col-md-4 col-lg-3">
<div className="text-center text-md-right">
<div className="d-inline loginDrop">
<Link href={!isAuthenticated ? "/login" : "/profile"} as={!isAuthenticated ? "/login" : "/profile"}>
<a className="signinBtn mr-5">{!isAuthenticated ? "Sign In" : "My Account"}</a>
</Link>
<div className={!isAuthenticated ? "login-content" : "login-content logout-content"}>
<p> </p>
<div className="login-inner">
<Link href={!isAuthenticated ? "/login" : "/profile"} as={!isAuthenticated ? "/login" : "/profile"}><a><FontAwesomeIcon icon={faUserCircle} className="mr-2"/> Your Profile</a></Link>
<Link href={!isAuthenticated ? "/login" : "/orders"} as={!isAuthenticated ? "/login" : "/orders"}><a><FontAwesomeIcon icon={faBoxOpen} className="mr-2 orderIcon"/> Orders</a></Link>
<Link href={!isAuthenticated ? "/login" : "/wishlist"} as={!isAuthenticated ? "/login" : "/wishlist"}><a><FontAwesomeIcon icon={faHeart} className="mr-2"/> Whishlist</a></Link>
<div className="otherDrop">
{!isAuthenticated ?
<>
<p className="first">Don't have an account?</p>
<p className="register"><Link href="/register" as="/register"><a>Register</a></Link></p>
<p className="login"><Link href="/login" as="/login"><a>Login</a></Link></p>
</>
:
<p className="login"><a href="#" onClick={deauthenticate}>Logout</a></p>
}
</div>
</div>
</div>
</div>
<Link href="/cart" as="/cart">
<a className="cartBtn"><FontAwesomeIcon icon={faShoppingCart} className="mr-xl-1"/> Cart <span>{carts[0] === null ? 0 : carts.length}</span></a>
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
}
export default Header;
Layout.js
import Head from 'next/head';
import * as Main from './Index'
import './styles/Index';
const Layout = ({ children, title }) => (
<div>
<Head>
<title>{ title }</title>
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<Main.Top/>
<Main.Header/>
<div>
{ children }
</div>
</div>
);
export default Layout;
next.config.js
const withSass = require('#zeit/next-sass')
module.exports = withSass({
cssLoaderOptions: {
url: false
}
})
Is there any problem with my code?
I am using sass for styling. What may be the issue. I have searched a lot and couldn't find any solution. Actually am new to next.js. So I am not able to find a solution.
As said in their docs, next/Link accept the props href and as, where:
href: The page that it should go for, this path will never change at runtime.
as: Something like a decorator, how the link should appears for the user. It can change in runtime.
Tha been said, lets take a look in one of yours Link's:
<Link href={"/products/"+trending.trending_slug} as={"/products/"+trending.trending_slug}><a>{trending.trending_name}</a></Link>
In this case your href is changing dynamic with your trending and it should be a page that exists in your project, like pages/product/trending and if trending is dynamic you can use pages/product/[trending] and then in the as property you should use the dynamic link, like you are already doing, /products/"+trending.trending_slug.
Take a look into their docs about it: https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes
Here is a issue that look's to be the same problem: https://github.com/vercel/next.js/issues/11157
Related
I'm having a hard time understanding how the routes and outlets work in react. My problem is this.
If I have a route that should load 3 parts.
-Top Menu
-Side Menu
-Center Content
But the center content is contained in the div thats wrapped by the "Side Menu" how do I wrap another element that will be changing inside of a previous component. My goal is to use the first 2 in all of the routes and based on the route the center content will change.
This is what it should look like
<div id="layoutSideNav">
<div id="layoutsidenav_nav"></div>
<div id="layoutSidenav_content"></div>
</div>
But for some reason all I can get is this
<div id="layoutSideNav">
<div id="layoutsidenav_nav"></div>
</div>
<div id="layoutSidenav_content"></div>
My react looks like this.
3 Components
Contains the top nav
contains the side nav
contains body elements that will change.
App()
<Route
path='/admin-dashboard'
element={
<>
<AdminNavigation />
<AdminNavigationLeft />
<AdminDashBoardHome />
</>
}
>
If I add <Outlet/> before the closing div in "layoutSideNav" component. nothing happens. If I remove the outlets from all components the app() looks the same. The top nav and side nave display correclty, but the center content is wonky.
I feel like routes is so much more abstract than I'm used to so maybe I'm just not thinking about it logically. Thank you so much for your help!
I tried using <Outlet/> to adjust how where the third component content displayed.
I've added my full code below for review.
const AdminNavigation = () =>{
const toggleSideMenu = event => {
// 👇️ toggle class on click
document.getElementsByTagName('body')[0].classList.toggle('sb-sidenav-toggled');
};
return (
<Fragment>
<nav className="sb-topnav navbar navbar-expand navbar-dark bg-dark">
<a className="navbar-brand ps-3" href="index.html">Woodmoore Improvement</a>
<button className="btn btn-link btn-sm order-1 order-lg-0 me-4 me-lg-0" onClick={toggleSideMenu} id="sidebarToggle" href="#!"><i className="fas fa-bars"></i></button>
<form className="d-none d-md-inline-block form-inline ms-auto me-0 me-md-3 my-2 my-md-0">
<div className="input-group">
<input className="form-control" type="text" placeholder="Search for..." aria-label="Search for..." aria-describedby="btnNavbarSearch" />
<button className="btn btn-primary" id="btnNavbarSearch" type="button"><i className="fas fa-search"></i></button>
</div>
</form>
<ul className="navbar-nav ms-auto ms-md-0 me-3 me-lg-4">
<li className="nav-item dropdown">
<a className="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"><i className="fas fa-user fa-fw"></i></a>
<ul className="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<li><a className="dropdown-item" href="#!">Settings</a></li>
<li><hr className="dropdown-divider" /></li>
<li><a className="dropdown-item" href="#!">Logout</a></li>
</ul>
</li>
</ul>
</nav>
</Fragment>
)
}
export default AdminNavigation;
const AdminDashBoardHome = () => {
return(
<Fragment>
<div id='layoutSidenav_content'>
<main>
<div className='container-fluid px-4'>
<h1 className='mt-4'>HOA Member Manager</h1>
<ol className='breadcrumb mb-4'>
<li className='breadcrumb-item active'>Member Map</li>
</ol>
<div className='row'>
<div className='col-lg-12'>
<div className='embed-responsive embed-responsive-16by9'>
<div id='map_canvas' className='embed-responsive-item pb-4' >
</div>
</div>
</div>
</div>
<div className='row'>
</div>
<div className='card mb-4'>
<div className='card-header'>
<i className='fas fa-table me-1'></i>
Member Lookup
</div>
<MemberDataList/>
</div>
</div>
</main>
<footer className='py-4 bg-light mt-auto'>
<div className='container-fluid px-4'>
<div className='d-flex align-items-center justify-content-between small'>
<div className='text-muted'>Copyright © Your Website 2022</div>
<div>
<a href='#'>Privacy Policy</a>
·
<a href='#'>Terms & Conditions</a>
</div>
</div>
</div>
</footer>
</div>
</Fragment>
)
}
export default AdminDashBoardHome;
const AdminNavigationLeft = () => {
document.body.classList.add('sb-nav-fixed');
return(
<Fragment>
<div id="layoutSidenav">
<Outlet/>
<div id="layoutSidenav_nav">
<nav className="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div className="sb-sidenav-menu">
<div className="nav">
<div className="sb-sidenav-menu-heading">Core</div>
<a className="nav-link" href="index.html">
<div className="sb-nav-link-icon"><i className="fas fa-tachometer-alt"></i></div>
Dashboard
</a>
<div className="sb-sidenav-menu-heading">Interface</div>
<a className="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts">
<div className="sb-nav-link-icon"><i className="fas fa-columns"></i></div>
Layouts
<div className="sb-sidenav-collapse-arrow"><i className="fas fa-angle-down"></i></div>
</a>
<div className="collapse" id="collapseLayouts" aria-labelledby="headingOne" data-bs-parent="#sidenavAccordion">
<nav className="sb-sidenav-menu-nested nav">
<a className="nav-link" href="layout-static.html">Static Navigation</a>
<a className="nav-link" href="layout-sidenav-light.html">Light Sidenav</a>
</nav>
</div>
<a className="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#collapsePages" aria-expanded="false" aria-controls="collapsePages">
<div className="sb-nav-link-icon"><i className="fas fa-book-open"></i></div>
Admin Management
<div className="sb-sidenav-collapse-arrow"><i className="fas fa-angle-down"></i></div>
</a>
<div className="collapse" id="collapsePages" aria-labelledby="headingTwo" data-bs-parent="#sidenavAccordion">
<nav className="sb-sidenav-menu-nested nav accordion" id="sidenavAccordionPages">
<a className="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#pagesCollapseAuth" aria-expanded="false" aria-controls="pagesCollapseAuth">
Manage Users
</a>
<a className="nav-link collapsed" href="#" data-bs-toggle="collapse" data-bs-target="#pagesCollapseAuth" aria-expanded="false" aria-controls="pagesCollapseAuth">
Create New
</a>
</nav>
</div>
</div>
</div>
<div className="sb-sidenav-footer">
<div className="small">Logged in as:</div>
Start Bootstrap
</div>
</nav>
</div>
</div>
</Fragment>
)
}
export default AdminNavigationLeft;
If the following is what you intend to be rendered:
<div id="layoutSideNav">
<div id="layoutsidenav_nav"></div>
<div id="layoutSidenav_content"></div>
</div>
Then I suspect you want the routed content to be rendered in the layoutSidenav_content div. Something like the following:
<div id="layoutSideNav">
<div id="layoutsidenav_nav">
... navbar content ...
</div>
<div id="layoutSidenav_content">
... routed content ...
</div>
</div>
In other words, the above snippet describes a layout component, the routed content is the logical place for an Outlet component wrapping nested routes to output their element content into. The route may look like:
const AdminLayout = () => (
<>
<AdminNavigation />
<div id="layoutsidenav">
<div id="layoutSidenav_nav">
<AdminNavigationLeft />
</div>
<div id="layoutsidenav_content">
<Outlet />
</div>
</div>
</>
);
<Route
path='/admin-dashboard'
element={<AdminLayout />}
>
<Route index element={<AdminDashBoardHome />} />
... other admin routes
</Route>
const AdminNavigationLeft = () => {
useEffect(() => {
document.body.classList.add('sb-nav-fixed');
}, []);
return (
<nav className="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div className="sb-sidenav-menu">
...
</div>
</nav>
)
}
const AdminDashBoardHome = () => {
return (
<Fragment>
<main>
...
</main>
<footer className='py-4 bg-light mt-auto'>
...
</footer>
</Fragment>
)
}
I solved my own question.
You need to run the props through the component you're trying to display. The solution should be like this.
App()
<Route path='/admin-dashboard' element={<><AdminNavigation /><AdminNavigationLeft><AdminDashBoardHome/></AdminNavigationLeft></>}>
AdminDashLeft()
const AdminNavigationLeft = (props) => {
{props.children} // This is where the child component should display
}
I am a new learner of graphql and I want someone to explain to me why I get this error thousnd of times I do not even know what it means here is the error :
Uncaught (in promise) Error: Missing Authorization header ('Authorization: ApiKey ').
here is my code:
render() {
console.log(this.state.minicart_product_count)
return (
<Mutation mutation={change_currency}>
{(convert,{error})=>{
return(
<div className="nav" >
<ul className="nav-list" >
<Link to="/"> <li onClick={this.handleclick} className="activ" >WOMEN</li></Link>
<Link to="/men"><li onClick={this.handleclick} >MEN</li></Link>
<Link to="/kids"><li onClick={this.handleclick}>KIDS</li></Link>
</ul>
<img src={logo} className="logo" />
<div className="icons" >
{this.state.minicart_product_count}
<img src={currency} className="currency"/>
<div className="select">
<option onClick={convert({
variables:{
amount: this.state.amount,
baseCurrency:this.state.baseCurrency,
quoteCurrencies:this.state.quoteCurrencies
}})}>$ USD</option>
<option>€ EURO</option>
<option>¥ JPY</option>
</div>
<img src={cart} className="bag" onClick={this.handlecartclick} onDoubleClick={this.cancelfunc} />
<div className="mini-cart" ref={this.minicart} >
{this.state.style}
<myContext.Consumer>
{function(value){
return (
<><div className="heading">
<h3>My Bag :</h3>{value.minicart.length+ " Items"}
</div>
<div className="products">
<div>{value.minicart.map((el) => el)}</div>
</div>
{value.minicart.length>1?<div className="total">Total <span>{value.minicart.reduce(function(acc,ele){return acc+ele.props.price},0)+"$"}</span></div>:value.minicart.length===0?<div className="empty">YOUR BAG IS EMPTY</div>:<div className="total">Total <span>{value.minicart[0].props.price+"$"}</span></div>}
</>)
}}
</myContext.Consumer>
<div>
<div className="buttons">
<Link to="/cart"><button>VIEW BAG</button></Link>
<button>CHECK OUT</button>
</div>
</div>
</div>
</div>
</div>
)
}}
</Mutation>
);
I have a problem. Link in component change Url in browser but not return component until i reload my browser.
I click product detail. Inside product detail have similar product.
I click on product details of similar products.
-> Browser Url update but it doesn't return product details until I reload the browser.
This is product in home:
<div className="col-md col-6">
<figure className="card-product-grid card-sm">
<Link to={`product-detail/${item.id}`} className="img-wrap item">
<img src={img_path + item.image} alt="null" />
</Link><div className="text-wrap p-3">{item.productName}
<span className="badge badge-danger"> {item.salePrice * 100 / item.price}
</span>
</div>
</figure>
</div>
This is similar product:
{productLike && productLike.length > 0 && productLike.map((item, index) => {
return <>
<Product key={index} id={item.id} image={item.image} productName={item.productName} detail={item.detail} price={item.price} />
This is Product component:
import React from "react";
import { Link } from "react-router-dom";
class Product extends React.Component {
render() {
var img_path = "http://localhost:8000/img/"
return (
<div class="col-md-3">
<figure class="card card-product-grid">
<div class="img-wrap">
<img src={img_path + this.props.image} alt="null" />
</div>
<figcaption class="info-wrap">
<h6 class="title" >{this.props.productName}</h6>
<Link to={`/product-detail/${this.props.id}`} class="title mb-2">{this.props.detail.indexOf('</') !== -1
? (
<div dangerouslySetInnerHTML={{ __html: this.props.detail.replace(/(<? *script)/gi, 'illegalscript') }} >
</div>
)
: this.props.detail
}</Link>
<div class="price-wrap">
<span class="price">{this.props.price}</span>
<small class="text-muted">/per bag</small>
</div>
<p class="mb-2"> 2 Pieces <small class="text-muted">(Min Order)</small></p>
<p class="text-muted ">Guangzhou Yichuang Electronic Co</p>
<hr />
<label class="custom-control mb-3 custom-checkbox">
<input type="checkbox" class="custom-control-input" />
<div class="custom-control-label">Add to compare
</div>
</label>
<i class="fa fa-envelope"></i> Contact supplier
</figcaption>
</figure>
</div>
);
}
}
export default Product;
Can someone help? Thank!
I have a frontend react app that have cards, search bar, and filters. So to map the cards that I have, I want to send a request to elasticsearch (port:9200) using axios to save all the data in array and map my cards as I want, can you please help me?
Edit: I update the code here and include all of it, but there is no card mapped
function CreateCards(NCARMap) {
return(
<SimpleCard
key={NCARMap.id}
theCardId={NCARMap.id}
cardType={NCARMap.approvetool}
cardNum={NCARMap.num}
cardName={NCARMap.name}
cardDate={NCARMap.date}
// cardCategory={NCARMap.cardCategory}
// cardSource={NCARMap.cardSource}
cardDesc={NCARMap.summary}
cardURL={NCARMap.image}
/>
);
}
//create the class
export default class OfficialDocument extends Component {
constructor(props) {
super(props);
this.state = {
NCARMap: [],
NCARMapAS: [],
};
}
componentDidMount(){
//Get NCARMap data, NCARMapAS used for filtring and sorting the cards
axios.get('http://localhost:9200/ncar_index/ncar/_search')
.then(resp => {
console.log(resp)
this.setState({
NCARMap: resp._source,
NCARMapAS:resp.data
})
console.log(this.state.NCARMap)
})
}
handleChange(event) {
const search_query = event.target.value;
}
render(){
return(
//HTML FILE Converted to React
<div>
<meta charSet="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta httpEquiv="X-UA-Compatible" content="ie=edge" />
<title>منشآت</title>
<link rel="shortcut icon" href="/images/favicon.png" type="image/x-icon" />
{/*============= ScrollToTop Section Starts Here =============*/}
<div className="overlayer" id="overlayer">
<div className="loader">
<div className="loader-inner" />
</div>
</div>
<i className="fas fa-angle-up" />
<div className="overlay" />
{/*============= ScrollToTop Section Ends Here =============*/}
{/*============= Header Section Starts Here =============*/}
<header className="header-section">
<div className="container">
<div className="header-wrapper">
<div className="logo-area">
<div className="logo">
<a href="/">
<img src="/images/logo/logo.png" alt="logo" />
</a>
</div>
<div className="support headFont">
الصفحة الرئيسية
</div>
</div>
<ul className="menu headFont">
<li>
{/*Here we need to change the herf link*/}
الوثائق و المحفوظات
</li>
<li>
الأخبار
</li>
<li>
{/*Here we need to change the herf link*/}
التغريدات
</li>
{/*Here we need to change the herf link*/}
{/* I want to know the diffrence between the two below */}
<li className="d-md-none text-center">
تسجيل دخول
</li>
</ul>
<div className="header-bar d-lg-none">
<span style={{backgroundColor: '#00A7CF'}} />
<span style={{backgroundColor: '#00A7CF'}} />
<span style={{backgroundColor: '#00A7CF'}} />
</div>
{/* <div class="header-right"> */}
{/*Here we need to change the herf link*/}
{/* تسجيل دخول
</div> */}
</div>
</div>
</header>
{/*============= Header Section Ends Here =============*/}
{/*============= Banner Section Starts Here =============*/}
<section className="banner-2 bg_img" data-background="/images/banner/background3.png">
<div className="container">
<div className="banner-content-2">
<h1 className="title cl-white">مرحباً بك في قسم الوثائق والمحفوظات</h1>
<p className=" cl-white">يحتوي هذا القسم على الوثائق والمحفوظات المعتمدة من المركز الوطني للوثائق والمحفوظات</p>
<form className="search-form round">
<input type="text" style={{textAlign: 'right', color: 'black'}} placeholder="... ابحث هنا" />
<button type="submit"><i className="flaticon-search" /> <span className="d-none d-sm-inline-block">ابحث</span></button>
</form>
</div>
</div>
</section>
{/*============= Banner Section Ends Here =============*/}
{/*============= How Search Section Starts Here =============*/}
<div className="how-search-section padding-bottom mt--93">
<div className="container">
<div className="row mb-30-none justify-content-center">
<div className="filter-rtl">
{/*begin::Body*/}
<div className="card-body filters">
{/*begin::Form*/}
<form>
{/*begin::Categories*/}
<div className="form-group mb-11">
<label className="font-size-h3 font-weight-bolder text-dark mb-7">التنصيفات</label>
{/* start dropdown menue */}
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
أداة الاعتماد
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">أمر ملكي</a>
<a class="dropdown-item" href="#">مرسوم ملكي</a>
<a class="dropdown-item" href="#">قرار مجلس الوزراء</a>
<a class="dropdown-item" href="#">أمر سامي</a>
<a class="dropdown-item" href="#">قرار وزاري</a>
<a class="dropdown-item" href="#">قرار مجالس وهيئات</a>
<a class="dropdown-item" href="#">قرار إداري</a>
<a class="dropdown-item" href="#">توجيه سامي</a>
</div>
</div>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
فئة الوثيقة
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#">الاتفاقيات و المعادات الدولية العامة</a>
<a class="dropdown-item" href="#">الاتفاقيات الدولية الثنائية</a>
<a class="dropdown-item" href="#">الاتفاقيات الدولية متعددة الأطراف</a>
</div>
</div>
</div>
{/* end dropdown menue */}
{/* Start: : DateRangePickerComponent */}
<DateRangePickerComponent></DateRangePickerComponent>
{/* End: : DateRangePickerComponent */}
{/*end::Categories*/}
<button type="submit" className="btn btn-primary font-weight-bolder mr-2 px-8">إعادة ضبط</button>
<button type="reset" className="btn-submit btn btn-clear font-weight-bolder text-muted px-8">بحث</button>
</form>
{/*end::Form*/}
</div>
{/*end::Body*/}
</div>
<div className="general-card">
{this.state.NCARMap.map(CreateCards)}
{console.log(this.state.NCARMap)}
</div>
</div>
</div>
</div>
{/*============= How Search Section Ends Here =============*/}
{/*============= Footer Section Starts Here =============*/}
<footer className="footer-section pt-70-145">
<div className="dot-slider bg_img" />
<div className="container">
<div className="row mb--50 justify-content-between">
<div className="col-sm-8 col-lg-4">
<div className="footer-widget widget-about">
</div>
</div>
</div>
</div>
<div className="footer-bottom cl-white">
<p>جميع الحقوق محفوظة © 2021</p>
</div>
</footer>
{/*============= Footer Section Ends Here =============*/}
</div>
)}
}
You need to add render method to your class component
export default class OfficialDocument extends React.Component {
constructor(props) {
super(props);
this.state = {
NCARMap: [],
NCARMapAS: [],
// need to add status
status: 'idle',
};
}
componentDidMount() {
//Get NCARMap data, NCARMapAS used for filtring and sorting the cards
this.setState({
status: 'pending',
});
axios
.get('http://localhost:9200/ncar_index/ncar/_search')
.then((resp) => {
console.log(resp);
this.setState({
NCARMap: resp._source,
NCARMapAS: resp.data,
status: 'success',
});
console.log(this.state.NCARMap);
})
.catch(() => {
this.setState({
status: 'error',
});
});
}
render() {
return (
<div>
{this.state.status === 'pending' && <div>Loading...</div>}
{this.state.status === 'error' && <div>Error</div>}
{this.state.status === 'success' && this.NCARMap.map((item) => {
return <CreateCards key={id} {...item} />;
})}
</div>
);
}
}
I answer this by receives them as objects:
code
<div className="general-card1">
{this.state.noPlaceFound ? (
<h3 className="noPlaceFound">
<i className="fas fa-exclamation-circle fa-sm WarnIcon"></i>
لا يوجد نتائج
</h3>
) : (
this.state.TweetsMap.map((v) => CreateCards(v._source))
)}
</div>
I have data that I am looping through and I have a slight issue with a dropdown menu. Whenever I click the dropdown button for a single post all the other posts open. And I don't know to solve it.
Here is the React code
const Post = () {
const [open, setOpen] = useState(false)
return(
{posts.map((post) => {
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && ( ------> here is where the problem comes
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})}
)
}
Here is a picture
Any help will suffice and I appreciate your time.
You're using the same state value for all items in your loop, so naturally they are going to all follow the same directive.
I would recommend creating a PostItem component that maintains its own state. Something like this:
const PostItem = ({post}) => {
const [open, setOpen] = useState(false)
return (
<div className="card" key={post.postId}>
<div className="card-header">
<div className="card-header__avatar">
<img
src="https://source.unsplash.com/user/erondu/40x40"
alt=""
/>
</div>
<div className="card-header__username">
<span>
<strong>
{post.firstname} {post.lastname}
</strong>
</span>
<br />
<span>
<small>{date}</small>
</span>
</div>
<div
className="card-header__moreBtn"
onClick={() => setOpen(!open)}
>
<img src={More} alt="" />
{open && (
<div class="dropdown-wrapper">
<ul class="dropdown-menu">
<li class="dropdown-menu__item">
<Link href="#d" onClick={deletePost}>Edit</Link>
</li>
<li class="dropdown-menu__item">
<Link className="dropdown-menu__item__link" onClick={deletePost}>Delete</Link>
</li>
</ul>
</div>
)}
</div>
</div>
<div className="postDescription">
<p>{post.postDescription}</p>
</div>
<div className="imgPost">
<img src={post.image} alt="" />
</div>
</div>
)
})
}
const AllPosts = ({posts}) {
return(
{posts.map(post => <PostItem post={post} />
)
}
Now each PostItem has a separate, internal instance of open in its own state and will act independently from the others.