I want when I press on the button it redirects me to the payment page.
import React,{useHistory, useState} from 'react'
import data from './data.json'
function GLC() {
let history = useHistory();
function handleClick() {
history.push("/payment");
}
return (
<div >
{data.map((postData) =>{
console.log(postData)
return(
<div key=
{postData.id}>
<div className='absolute '>
<img className='w-screen object-contain'src="./ModImages/Gclass.jpg"></img>
<h1 className='absolute ml-24 md:text-5xl sm:text-5xl top-8'>Class G</h1>
<h1 className='absolute text-base font-mono ml-24 top-24'>$43,600</h1>
<button onClick={handleClick} className=' absolute text-black-600 h-10 top-24 ml-24 mt-32 bg-
white w-36 rounded-full focus:outline-none focus:ring-2 focus:ring-gray-600'>BuyNow</button>
</div>
</div>
)
})
}
</div>
)
}
export default GLC
// Make sure you alreadly installed the react-router-dom package.
import { useHistory } from 'react-router-dom';
function GLC() {
const history = useHistory();
function handleClick() {
history.push("/payment");
}
// ...
}
Then you can work .
Related
picture of the output https://i.stack.imgur.com/5kxvb.png
code of the carousel
import React from 'react'
import AliceCarousel from 'react-alice-carousel';
import { Link } from 'react-router-dom';
import UseAxios from '../hooks/UseAxios'
import "./Trending.css";
const Trending = () => {
const { response } = UseAxios("search/trending");
return (
{response && response.coins.map(coin => {
return <div className='flex slide' key={coin.item.coin_id}>
<Link to={`/coin/${coin.item.id}`}>
<div>
<AliceCarousel
mouseTracking
infinite
autoPlayInterval={1000}
animationDuration={1500}
disableButtonsControls
autoPlay
>
<img src={coin.item.large} className="mt-0 relative top-30 img" />
<p key={coin.item.coin_id} className="name"> {coin.item.name} </p>
</AliceCarousel>
</div>
</Link>
</div>
})}
</div>
)
}
export default Trending;
note:- library being used is AliceCarousel.
can someone please help me fix the carousel.
The problem is about that is taking long time to response another route. It seems next router's error and it can cause by this ("getServerSideProps"). How can I change with this code to another or did I need to change react router instead? This is index which used ("getServerSideProps") -
import axios from 'axios';
import VideoCard from '../components/VideoCard';
import { BASE_URL } from '../utils';
import { Video } from '../types';
import NoResults from '../components/NoResults';
interface IProps {
videos: Video[];
}
const Home = ({ videos }: IProps) => {
return (
<div className='flex flex-col gap-10 videos h-full'>
{videos.length
? videos?.map((video: Video) => (
<VideoCard post={video} isShowingOnHome key={video._id} />
))
: <NoResults text={`No Videos`} />}
</div>
);
};
export default Home;
export const getServerSideProps = async ({
query: { topic },
}: {
query: { topic: string };
}) => {
let response = await axios.get(`${BASE_URL}/api/post`);
if(topic) {
response = await axios.get(`${BASE_URL}/api/discover/${topic}`);
}
return {
props: { videos: response.data },
};
};
This is from another code with that used next router
import React, { useState } from 'react';
import { NextPage } from 'next';
import { useRouter } from 'next/router';
import Link from 'next/link';
import { AiFillHome, AiOutlineMenu } from 'react-icons/ai';
import { ImCancelCircle } from 'react-icons/im';
import SuggestedAccounts from './SuggestedAccounts';
import Discover from './Discover';
import Footer from './Footer';
import useAuthStore from '../store/authStore';
const Sidebar: NextPage = () => {
const [showSidebar, setShowSidebar] = useState<Boolean>(true);
const { pathname } = useRouter();
const { fetchAllUsers, allUsers }: any = useAuthStore();
const activeLink = 'flex items-center gap-3 hover:bg-primary p-3 justify-center xl:justify-start cursor-pointer font-semibold text-[#F51997] rounded';
const normalLink = 'flex items-center gap-3 hover:bg-primary p-3 justify-center xl:justify-start cursor-pointer font-semibold rounded';
return (
<div>
<div
className='block xl:hidden m-2 ml-4 mt-3 text-xl'
onClick={() => setShowSidebar(!showSidebar)}
>
{showSidebar ? <ImCancelCircle /> : <AiOutlineMenu />}
</div>
{showSidebar && (
<div className='xl:w-400 w-20 flex flex-col justify-start mb-10 border-r-2 border-gray-100 xl:border-0 p-3 '>
<div className='xl:border-b-2 border-gray-200 xl:pb-4'>
<Link href='/'>
<div className={pathname === '/' ? activeLink : normalLink}>
<p className='text-2xl'>
<AiFillHome />
</p>
<span className='capitalize text-xl hidden xl:block'>
For You
</span>
</div>
</Link>
</div>
<Discover />
<SuggestedAccounts
fetchAllUsers={fetchAllUsers}
allUsers={allUsers}
/>
<Footer />
</div>
)}
</div>
);
};
export default Sidebar;
I want to add spinner while loading data from database. For fetching data I am using react-hook. Here is my code ,how can I add spinner here?
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
return (
<>
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>
</>
);
};
export default Inventories;
It take a little bit time to load data from mongodb. So I want to add spinner loading before that.
You can do solution with useEffect. Basically initial loading is true and it becomes false when you have inventories data. I also see that you are using tailwind so you can set spinner icon animation directly with animate-spin
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
const [loading, setLoading] = useState(true)
useEffect(() => {
if(inventories?.length > 0) {
setLoading(false)
}
}, [inventories])
return (
<>
{loading <SpinnerComponent/> }
{!loading
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>}
</>
);
};
export default Inventories;
I'm writing a test to render my App component in the child there's a dashboard component where I'm using headless UI it working fine on localhost but getting undefined components on rendering on test how can I render them?
I'm trying to mock the render but no success yet it always rendering as undefined
App.test
import { render } from '#testing-library/react';
import { SnackbarProvider } from 'notistack';
import React from 'react';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { applyMiddleware, createStore } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import App from './App';
// import { rootReducer } from './store';
jest.mock('#headlessui/react', () => ({
...jest.requireActual('#headlessui/react'),
}));
describe('', () => {
function renderApp(
store = {},
// createStore(
// rootReducer,
// {},
// composeWithDevTools(applyMiddleware(thunk))
// ),
props = {}
) {
return render(
<SnackbarProvider>
<MemoryRouter>
{/* <Provider store={store}> */}
<App />
{/* </Provider> */}
</MemoryRouter>
</SnackbarProvider>
);
}
test('test render app component', async () => {
renderApp();
});
});
Component failing on test
import React, { Fragment, useState, useMemo, useEffect } from 'react';
import { Menu, Transition } from '#headlessui/react';
import { ChevronDownIcon } from '#heroicons/react/solid';
// import { useSelector, useDispatch } from 'react-redux';
// import types from '../../store/actions/types';
// NOTE - for ref this is happening globally now
// and it has the global styles taken out of it
// so it doesn't mess with other stuff hopefully
// import './tailwind-style.scss'
function classNames(...classes) {
return classes.filter(Boolean).join(' ');
}
const AdvertSwitch = () => {
console.log({ Menu, Transition });
// const dispatch = useDispatch()
const advertisersFromState = [
{
id: 1,
name: 'advertiser-one',
},
{
id: 2,
name: 'advertiser-two',
},
];
const advertisers = advertisersFromState;
const selectedAdvertiser = advertisersFromState[0];
const handleAdvertSwitch = (advertiser) => {
console.log('handle advertiser switch', advertiser);
};
const showMultiple = true;
const Single = () => {
return (
<div className="">
<div>{selectedAdvertiser?.name ?? 'loading...'}</div>
</div>
);
};
const Multiple = () => {
// } else {
return (
<div className="w-full bg-gray-200 flex justify-end">
<Menu as="div" className="ml-3 z-10 relative inline-block text-left">
<div>
<Menu.Button className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-transparent ">
{selectedAdvertiser?.name ?? 'loading...'}
<ChevronDownIcon
className="-mr-1 ml-2 h-5 w-5"
aria-hidden="true"
/>
</Menu.Button>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none">
<hr className="h-1 p-0 m-0" />
<div className="py-1">
{advertisers.map((advertiser) => {
return (
<Menu.Item key={advertiser.id}>
{({ active }) => (
<div
className={classNames(
active
? 'bg-gray-100 text-gray-900'
: 'text-gray-700',
'block px-4 py-2 text-sm'
)}
onClick={() => handleAdvertSwitch(advertiser)}
>
{advertiser?.name ?? 'loading...'}
</div>
)}
</Menu.Item>
);
})}
</div>
</Menu.Items>
</Transition>
</Menu>
</div>
);
};
return (
<div className="mr-2">
{showMultiple && <Multiple />}
{!showMultiple && <Single />}
</div>
);
};
export default AdvertSwitch;
Failing Test Snap
I have a little problem, I try to build a language learning website using React,
this is my initial homepage, and when i try to search for a word and that word doesn't exist in the database my website it s supposed to say "we can't find the word in our database" but that message it's generated on the top on my slideshow.. like
And i literally don't know what can i do..
my homepage code:
import React from 'react';
import Carousel from 'react-bootstrap/Carousel';
import pozika from '../images/telescop.png';
import '../../src/Ceseseu.css';
import pozika2 from '../images/door.png';
import pozika3 from '../images/threeword.png';
import pozaAbout from '../images/learnkorean.jpg';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import NavbarFunction from '../pages/NavBarAndSearchSentence';
import { faCheckSquare } from '#fortawesome/free-solid-svg-icons';
function HomePageSlideShow() {
return (
<>
<div className='test '>
<Carousel>
{/* <div className='letsDoIt'> */}
<Carousel.Item interval={1000}>
<img
className='d-block w-100'
width={900}
height={500}
src={pozika}
alt='First slide'
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
{/* </div> */}
<Carousel.Item interval={1000}>
<img
className='d-block w-100 '
src={pozika2}
alt='Third slide'
width={100}
height={500}
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item interval={1000}>
<img
className='d-block w-100'
src={pozika3}
alt='Third slide'
width={900}
height={500}
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</div>
</>
);
}
function HomePage() {
return (
<>
<HomePageSlideShow />
</>
);
}
export default HomePage;
and my function for searching process it s in another class, same class with my nav bar
import React from 'react';
import SentencesByWord from './SentencesByWord';
import { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Nav, Form, FormControl, Button } from 'react-bootstrap';
function NavbarFunction() {
const [sentence, setSentence] = useState('');
const [fetchu, setFetchu] = useState('');
const [error, setError] = useState('');
let history = useHistory();
const FetchData = () => {
fetch(`http://localhost:8080/words/showSentences?word=` + sentence)
.then((response) => response.json())
.then(setFetchu)
.then(console.log(fetchu))
.catch(function (error) {
console.log('mergi');
setError("We can't find the word in our database");
});
history.push('/home');
};
const OnChangerr = (e) => {
setSentence(e.target.value);
};
const HandleKeypress = (e) => {
if (e.keyCode === 13) {
FetchData();
}
};
return (
<>
<div className='inlineu'>
<Navbar bg='dark' variant='dark'>
<Navbar.Brand href='Home'>LearningVocab</Navbar.Brand>
<Nav className='mr-auto'>
<Nav.Link href='GiveMeSentences'>
Random Sentences
</Nav.Link>
<Nav.Link href='SendEmail'>
Send us your thoughts
</Nav.Link>
<Nav.Link href='SearchByWord'>Pricing</Nav.Link>
</Nav>
<Form inline>
<FormControl
type='text'
placeholder='Search'
className='mr-sm-2'
onChange={OnChangerr}
onKeyDown={HandleKeypress}
/>
<Button variant='outline-info' onClick={FetchData}>
Search
</Button>
</Form>
</Navbar>
</div>
{fetchu ? (
<div>
<h1> {fetchu.korfirstSentence} </h1>
<h1>{fetchu.kosecondSentence}</h1>
<h1>{fetchu.kothirdSentence}</h1>
<h1>{fetchu.kowordTranslation}</h1>
<h1>{fetchu.kowordId}</h1>
</div>
) : (
// <h1> {fetchu.kosecondSentence} </h1>
<h1 className='someSpace'>{error}</h1>
)}
</>
);
}
export default NavbarFunction;
i used boostrap for css
My react component tree: