function interpolations in a mapped component - javascript

below is couple of function (its inside a fictional component that's mapped over) , so i need help in a way to make this functions more dynamic . i appreciate the feedback
import { FC } from "react";
import {
questionOption1Variant,
questionOption2Variant,
dividerVariant,
} from "../animations/questionAnimation";
import { motion } from "framer-motion";
import { useAppSelector, useAppDispatch } from "../App";
import { countriesActions1 } from "../redux/fetch1";
import { countriesActions2 } from "../redux/fetch2";
import { useNavigate } from "react-router-dom";
import ResultBox1 from "./ResultBox1";
import ResultBox2 from "./ResultBox2";
const Question1: FC = () => {
const country = useAppSelector((state) => state.countries1);
const dispatch = useAppDispatch();
const navigate = useNavigate();
const firstChoiseHandler = () => {
dispatch(countriesActions1.chooseCountry1());
dispatch(countriesActions2.setQuestion());
setTimeout(() => navigate("/q2"), 2500);
};
const secondChoiseHandler = () => {
dispatch(countriesActions1.chooseCountry2());
dispatch(countriesActions2.setQuestion());
setTimeout(() => navigate("/q2"), 2500);
};
return (
<div className="grid grid-cols-3 h-screen w-screen">
<motion.div
variants={questionOption1Variant}
initial="hidden"
animate="visible"
exit="exit"
className="flex flex-col justify-center items-center pl-52"
>
<div>
<img
src={country.questionOption1.image}
alt="flag"
className={
country.correctAnswer1
? `rounded-full border-primary-200 border-8 h-80 w-80`
: `rounded-full border-red-500 border-8 h-80 w-80 transition-all duration-300 ease-in-out`
}
/>
</div>
<div className="my-5">
<h1 className="text-3xl font-rubik font-semibold text-secondary-200 uppercase">
{country.questionOption1.title}
</h1>
</div>
<button
className="my-5 mdbt primarybt uppercase"
onClick={firstChoiseHandler}
>
Correct Answer
</button>
<ResultBox1 country={country} />
</motion.div>
<div className="relative">
<svg
version="1.1"
id="Capa_1"
xmlns="http://www.w3.org/2000/svg"
x="0px"
y="0px"
viewBox="0 0 14.707 20.3"
className="enable-background:new 0 0 18.707 18.707;"
>
<motion.g
variants={dividerVariant}
initial="hidden"
animate="visible"
>
<rect
x="6.275"
y="0"
className="fill-black"
width="0.5"
height="20.3"
/>
</motion.g>
</svg>
</div>
<motion.div
variants={questionOption2Variant}
initial="hidden"
animate="visible"
exit="exit"
className="flex flex-col justify-center items-center pr-52 "
>
<div>
<img
src={country.questionOption2.image}
alt="flag"
className={
country.correctAnswer2
? `rounded-full border-primary-200 border-8 h-80 w-80`
: `rounded-full border-red-500 border-8 h-80 w-80 transition-all duration-300 ease-in-out`
}
/>
</div>
<div className="my-5">
<h1 className="text-3xl font-rubik font-semibold text-secondary-200 uppercase">
{country.questionOption2.title}
</h1>
</div>
<button
className="my-5 mdbt primarybt uppercase"
onClick={secondChoiseHandler}
>
Correct Answer
</button>
<ResultBox2 country={country} />
</motion.div>
</div>
);
};
export default Question1;
in above i wanted the second import to be dynamic so it will only add +1 to the fist import instead of hard coding it as 2
import { countriesActions1 } from "../redux/fetch1";
import { countriesActions2 } from "../redux/fetch2";
in below i wanted the number 1 & 2 to be dynamic , lets say i have data (which an array of objects) each object contains an id of 1 ,2 ,3 ...ect , how i can make it dynamic based on that
const country = useAppSelector((state) => state.countries1);
const firstChoiseHandler = () => {
dispatch(countriesActions1.chooseCountry1());
dispatch(countriesActions2.setQuestion());
setTimeout(() => navigate("/q2"), 2500);
};

Related

I am getting this error: The prop value with an expression type of Chain Expression could not be resolved. Please file is Failed to compile

Error:
./src/components/Main.jsx 26:12
Module parse failed: Unexpected token (26:12)
You may need an appropriate loader to handle this file type.
|
| var turncateString = function turncateString(str, num) {
if (str?.length > num) {
| return str.slice(0, num) + '....';
| } else {
Code:
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import requests from "../Requests";
import axios from "axios";
const Main = () => {
const [movies, setMovies] = useState([]);
const movie = movies[Math.floor(Math.random() * movies.length)];
useEffect(() => {
axios.get(requests.requestPopular).then((response) => {
setMovies(response.data.results);
});
}, []);
// console.log(movie)
const turncateString = (str, num) => {
if (str?.length > num) {
return str.slice(0, num) + "....";
} else {
return str;
}
};
return (
<div className="w-full h-[550px] text-white">
<div className="w-full h-full">
<div className="absolute w-full h-[550px] bg-gradient-to-r from-black"></div>
<img
className="w-full h-full object-cover"
src={`https://image.tmdb.org/t/p/original/${movie?.backdrop_path}`}
alt={movie?.title}
/>
<div className="absolute w-full top-[40%] p-4 md:p-8">
<h1 className="text-3xl md:text-5xl font-bold">{movie?.title}</h1>
<div className="my-4">
<button className="border bg-gray-300 text-black border-gray-300 py-2 px-5">
Play
</button>
<button className="border text-gray-300 border-gray-300 py-2 px-5 ml-4">
Watch Later
</button>
</div>
<p className="text-gray-400 text-sm">
Released: {movie?.release_date}
</p>
<p className="w-full md:max-w-[70%] lg:max-w-[50%] xl:max-w-[35%] text-gray-200">
{turncateString(movie?.overview, 150)}
</p>
</div>
</div>
</div>
);
};
export default Main;
enter code here

react useRef in carousel

I have a carousel that prints out a lists of data, 5 in total,
the issue is when I click on the next of any of the carousel buttons,
only the bottom carousel updates.
Any suggestions?
Here is my react tailwind code :
// query all available genres and for it create a listview row of the content
import { useState, useRef, useEffect } from "react";
import React from "react";
import ShowList from "./showlist.json";
import "./carousel.css";
import data from "./data.json";
export default function Genre() {
const maxScrollWidth = useRef(0);
const [currentIndex, setCurrentIndex] = useState(0);
const listCarousel = useRef(0);
const containerCarousel = useRef(0);
const movePrev = () => {
if (currentIndex > 0) {
setCurrentIndex((prevState) => prevState - 1);
}
};
const moveNext = () => {
if (
listCarousel.current !== null &&
listCarousel.current.offsetWidth * currentIndex <= maxScrollWidth.current
) {
setCurrentIndex((prevState) => prevState + 1);
}
};
const isDisabled = (direction) => {
if (direction === "prev") {
return currentIndex <= 0;
}
if (direction === "next" && listCarousel.current !== null) {
return (
listCarousel.current.offsetWidth * currentIndex >= maxScrollWidth.current
);
}
return false;
};
useEffect(() => {
if (listCarousel !== null && listCarousel.current !== null) {
listCarousel.current.scrollLeft = listCarousel.current.offsetWidth * currentIndex;
}
}, [currentIndex]);
useEffect(() => {
maxScrollWidth.current = listCarousel.current
? listCarousel.current.scrollWidth - listCarousel.current.offsetWidth
: 0;
}, []);
const DisplayData = ShowList.map((value, itemIndex) => {
let imageList = value.Shows.map((item) => {
return item;
});
return (
<section>
<div
ref={containerCarousel}
className="carousel my-12 mx-auto"
>
<h1 className="text-3xl leading-8 font-bold mb-12 text-slate-700">
{value.name}
</h1>
<div
className="relative overflow-hidden">
<div className="flex justify-between absolute top left w-full h-full">
<button
onClick={movePrev}
className="hover:bg-blue-900/75 text-white w-10 h-full text-center opacity-75 hover:opacity-100 disabled:opacity-25 disabled:cursor-not-allowed z-10 p-0 m-0 transition-all ease-in-out duration-300"
disabled={isDisabled("prev")}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-12 w-20 -ml-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15 19l-7-7 7-7"
/>
</svg>
<span className="sr-only">Prev</span>
</button>
<button
onClick={moveNext}
className="hover:bg-blue-900/75 text-white w-10 h-full text-center opacity-75 hover:opacity-100 disabled:opacity-25 disabled:cursor-not-allowed z-10 p-0 m-0 transition-all ease-in-out duration-300"
disabled={isDisabled("next")}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-12 w-20 -ml-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M9 5l7 7-7 7"
/>
</svg>
<span className="sr-only">Next</span>
</button>
</div>
<div
ref={listCarousel}
className="carousel-container relative flex gap-1 overflow-hidden scroll-smooth snap-x snap-mandatory touch-pan-x z-0"
>
{imageList.map((img, index) => {
return (
<ul>
<li
key={index}
className="carousel-item text-center relative w-64 h-64 snap-start"
>
<a
href={img.link}
className="h-full w-full aspect-square block bg-origin-padding bg-left-top bg-cover bg-no-repeat z-0"
style={{ backgroundImage: `url(${img.image || ""})` }}
>
<img
src={img.image || ""}
alt={img.title}
className="w-full rounded aspect-square hidden"
/>
</a>
<a
href={img.link}
className="h-full w-full aspect-square block absolute top-0 left-0 transition-opacity duration-300 opacity-0 hover:opacity-100 bg-blue-800/75 z-10"
>
<h3 className="text-white py-6 px-3 mx-auto text-xl">
{img.title}
</h3>
</a>
</li>
</ul>
);
})}
</div>
</div>
</div>
</section>
);
});
return <div>{DisplayData}</div>;
}
here is my data json file:
https://drive.google.com/file/d/1G0wInErDa2bUHGjn-TNDfTVXJru0QlaY/view?usp=sharing

Uncaught TypeError: DroppedItem.map is not a function ReactJS

I get the error "Uncaught TypeError: DroppedItem.map is not a function ReactJS" when trying to show a floating window on my page after opening a case. I think it has something to do with renders (https://jsramblings.com/are-you-logging-the-state-immediately-after-updating-it-heres-why-that-doesnt-work/) but I got no idea how to fix it. Please help. I use Axios to load arrays from my backend server. The "className" is from TailWind.
import {useEffect, useState, useContext} from "react"
import {useLocation} from 'react-router-dom'
import Axios from "axios";
import { AppContext } from "/src/App";
export default function CaseDetail(){
const [ContentList, setContentList] = useState([])
const [Case, setCase] = useState([])
const [ShowDrop, setShowDrop] = useState(false)
const [DroppedItem, setDroppedItem] = useState([])
const { token } = useContext(AppContext);
const { setToken } = useContext(AppContext);
const { userID } = useContext(AppContext);
const DroppedItemFunc = (array) => {
setDroppedItem(array)
}
const DropWindow = () => {
setShowDrop(!ShowDrop)
}
const MilSpecList = ContentList.filter(function(driver){
return driver.RarityName === "Mil-Spec"
})
const openCase = (CasePrice) => {
const Price = parseInt(CasePrice)
if (token >= Price){
setToken(token-Price)
const randomNumero = Math.random()* 100;
if(randomNumero <= 70)
{
const millength = MilSpecList.length
const randomItemM = Math.floor(Math.random() * (millength - 0)+ 0)
console.log(MilSpecList[randomItemM].SkinName)
console.log(MilSpecList[randomItemM].IDItem)
submitItem(MilSpecList[randomItemM].IDItem)
setDroppedItem(MilSpecList[randomItemM])
setShowDrop(!ShowDrop)
}
}else{console.log("No funds")}
}
return(
<div className="flex justify-center align-bottom">
{ShowDrop && <div className=" absolute">
{DroppedItem.map(item => (
<div className=" border-2 border-slate-500 w-[25rem] h-[30rem] p-1.5 px-2 m-2 box-content rounded-cool bg-slate-700 ">
<button
className=' border-2 border-green-700 bg-green-400 hover:bg-green-600 text-green-900 hover:text-rose-50 w-[100%] h-10 rounded-cool '
onClick={()=>{DropWindow()}}
>
Close
</button>
</div>
))}
</div>
}
<div className="bg-slate-800 rounded-cool text-white divide-y-2 w-3/5 p-3">
{Case.map(item => (
<h1 key={item.CaseName} className="text-4xl font-bold text-slate-200 py-2" >
{item.CaseName} 💼
</h1>
))}
{Case.map(item => (
<div key={item.CaseName} className="flex justify-center p-3 mt-2">
<div className=" w-[50%] p-1.5 px-2 m-2 box-content rounded-cool bg-slate-700 "
>
<div className="flex justify-center">
<img className="" src={`src/images/${item.CaseImage}`}/>
</div>
<h1 className="hover:text-orange-300">
{item.CaseName}
</h1>
<h1 className="hover:text-orange-300 basis-1/2">
{item.CasePrice} Tokens
</h1>
<div className=" flex justify-center">
<button className=" cursor-pointer text-xl text-slate-900 w-40 h-10 hover:text-orange-300 hover:bg-slate-600 hover:border-2 hover:border-white-200 bg-orange-300 rounded-cool px-2 py-0.25 transition-all"
onClick={() => {openCase(item.CasePrice)}}
>
OPEN
</button>
</div>
</div>
</div>
))}
</div>
</div>
)
}
your error is here: setDroppedItem(MilSpecList[randomItemM]) - you cannot modify the data type of your state from an array, to some other value, as the method 'map' no longer becomes available. Try to make sure you do not modify data structures, I find that prop-types (when in reactJS), typescript (when in reactTS), and eslint (in general) help me a lot to make sure I don't accidentally mutate my structure type on accident. Try also console logging the value and type of MilSpecList[randomItemM] to confirm the type is indeed an array, as well as anywhere you might be running setDroppedItem

How to hide a custom toast notification with Tailwind css and react

Im working on a custom toast notification. But the hard part to me is I've not been able to hide the toast notification correctly. When I make a click to show it the toast has an animation to the left the problem is when the toast is gonna hide just disapear and it does not slide to the right. Im working with react and tailwind css. Here is the code. also leave a link to the case. https://codesandbox.io/s/toast-notification-ucx2v?file=/src/components/toastNotification.jsx
I hope you can help me guys.
-----App component-----
import { useEffect, useState } from "react";
import ToastNotification from "./components/toastNotification";
import "./styles.css";
export default function App() {
const [showToast, setShowToast] = useState(false);
const addToCart = () => {
setShowToast(true);
};
useEffect(() => {
setTimeout(() => {
setShowToast(false);
}, 3000);
}, [showToast]);
return (
<div className="App">
<ToastNotification showNotification={showToast} />
<button
className="w-1/2 p-2 flex items-center justify-center rounded-md bg-indigo-400 text-white"
type="submit"
onClick={addToCart}
>
Add to cart
</button>
</div>
);
}
-----Toast component-----
import React, { useEffect, useState } from "react";
const ToastNotification = ({ showNotification }) => {
useEffect(() => {
setTimeout(() => {}, 5000);
}, []);
return (
<>
{showNotification === false ? null : (
<div className="static z-20">
<div
className={`${
showNotification
? "animate__animated animate__slideInRight absolute top-16 right-4 flex items-center text-white max-w-sm w-full bg-green-400 shadow-md rounded-lg overflow-hidden mx-auto"
: "animate__animated animate__slideOutRight absolute top-16 right-4 flex items-center text-white max-w-sm w-full bg-green-400 shadow-md rounded-lg mx-auto"
}`}
>
<div class="w-10 border-r px-2">
<i class="far fa-check-circle"></i>
</div>
<div class="flex items-center px-2 py-3">
<div class="mx-3">
<p>add to car</p>
</div>
</div>
</div>
</div>
)}
</>
);
};
export default ToastNotification;

Looping through array within Sanity Io React

I'm using react with sanity io to create a portfolio page. I would like to create an unordered list according to how many tags I have a on a project. A project is composed of a title, image, description, and tags(this is just an array).
What I have tried is:
{project.tags.map(type => {
return (
<li>{type.type.name}</li>
)
})}
And I keep getting the error: "TypeError: project.forEach is not a function". If I just render
{project.tags}
all of the tags are displayed but then I can't style them hence the need to put them into a list.
Does anyone know how to accomplish this?
import React, { useEffect, useState} from "react";
import sanityClient from "../client.js";
import '../index.css';
export default function Project() {
const [projectData, setProjectData] = useState(null);
useEffect(() => {
sanityClient.fetch(`*[_type == "project"] | order(index) {
title,
mainImage{
asset->{
_id,
url
},
},
description,
projectType,
link,
tags
}`).then((data) => setProjectData(data)).catch(console.error);
}, []);
return (
<div className="antialiased text-gray-800 bg-gray-400">
<div className="container relative flex flex-col px-6 mx-auto space-y-8">
<div className="absolute inset-0 z-0 w-2 h-full bg-white shadow-md left-38 md:mx-auto md:right-0 md:left-0"></div>
{projectData && projectData.map((project, index)=> (
<div className="relative z-10 p-10 ">
<img src={project.mainImage.asset.url} alt={project.mainImage.alt} className="timeline-img" />
<div className={`${index % 2 === 0 ? "timeline-container-left timeline-container" : "timeline-container" }`} >
<p className="font-bold uppercase">{project.title}</p>
<div className={`${index % 2 === 0 ? "timeline-pointer-left timeline-pointer" : "timeline-pointer" }`} aria-hidden="true"></div>
<div className="p-6 bg-white rounded-md shadow-md sm:p-2">
<p className="pt-1">{project.description}</p>
</div>
</div>
</div>
))}
</div>
</div>
)
}
{project.tags.map( type => ( {type} ))} is the answer.

Categories