Setting timer for my carousel in Next js using tailwinds - javascript

I want to set a slider where by after 3 seconds, it slides to next image. I have tried different custom css but none seems to work. I am using a carousel component in flow bite.
import { Carousel } from "flowbite-react";
export default function Slider() {
return (
<div className="h-56 sm:h-64 xl:h-80 2xl:h-96">
<Carousel>
<img
src="carousel-1.jpg"
alt="..."
/>
<img
src="carousel-2.jpg"
alt="..."
/>
</Carousel>
</div>
);
}

There are different ways to do it, but the easiest approach is to use method flow bite has already provided. add slideInterval={3000} in your <Carousel/> component
import { Carousel } from "flowbite-react";
export default function Slider() {
return (
<div className="h-56 sm:h-64 xl:h-80 2xl:h-96">
<Carousel slideInterval={3000}>
<img
src="carousel-1.jpg"
alt="..."
/>
<img
src="carousel-2.jpg"
alt="..."
/>
</Carousel>
</div>
);
}

You can do this by using setTimeout or setInterval to update the state of the carousel.
Here is an example:
import { useState, useEffect } from "react";
import { Carousel } from "flowbite-react";
export default function Slider() {
const [activeIndex, setActiveIndex] = useState(0);
const images = ["carousel-1.jpg", "carousel-2.jpg"];
useEffect(() => {
const interval = setInterval(() => {
setActiveIndex((activeIndex + 1) % images.length);
}, 3000);
return () => clearInterval(interval);
}, [activeIndex, images.length]);
return (
<div className="h-56 sm:h-64 xl:h-80 2xl:h-96">
<Carousel activeIndex={activeIndex} onSelect={setActiveIndex}>
{images.map((image) => (
<img key={image} src={image} alt="..." />
))}
</Carousel>
</div>
);
}
In this example, useState stores the index of the active image and useEffect sets the timer. In useEffect the setInterval updates the index of the active image every 3 seconds. The clearInterval clears the timer when the component is disassembled. Next we pass the index of the active image and a setActiveIndex function to the Carousel component and render the images using a map.

Related

img src not responding in reactjs

this is my row.js code:
import React, { useEffect, useState } from 'react';
import axios from './axios';
const base_URL="https://image.tmdb.org/t/p/original";
function Row({title,fetchUrl}) {
const [movies,setMovies]=useState([]);
useEffect(()=>{
async function fetchData(){
const request=await axios.get(fetchUrl);
console.log(request);
setMovies(request.data.results);
return request;
}
fetchData();
},[fetchUrl]);
return (
<div className="row">
<h2>{title}</h2>
<div className="row__posters">
{movies.map(movie=>{
console.log(movie);
<img src={'${base_URL}${movie.poster_path}'} alt={movie.name}/>
})}
</div>
</div>
)
}
export default Row
My screen should display the posters of films but its not displaying it, I wonder there is some problem in movies.map...... part and img src="......" part
You need to return image:
<div className="row__posters">
{movies.map(movie=>{
console.log(movie);
return <img src={'${base_URL}${movie.poster_path}'} alt={movie.name}/>
})}
</div>
you only map the movies object instead returning .Hence try this:
{movies.map((movie,index)=>{
console.log(movie);
return ( <img key={index} src={'${base_URL}${movie.poster_path}'} alt={movie.name}/>)
})}
here , also use key = {index} within img tag.It gives the unique key to each img tag iteratively .

How to access the state of a component at a superior level without using useContext?

let me explain my question.
I would like to create expanding flex cards, here is the exemple on codepen : https://codepen.io/z-/pen/OBPJKK
and here is my code for each button :
basically I have a component which is called HomeButtons that generates every flex cards. Inside this component I have a smaller component called readMore. In this component I have a useState that allows me to toggle individually each button to add or retreive an active class. If the active class is present, that means that the selected button must expand and the other ones must shrink.
What I would like to do is to access the readMore state ouside of the readMore subcomponent. That way I could write a function to remove the active class from a card if the user clicks on another card like so :
function setToUnactive() {
if (readMore(true)) {
readMore(false)}
}
My question is how can I get the state of readMore outside of the readMore subcomponent ? Do I need to use useContext ? Because that seems very simple to do but I tried a lot of things and nothing works. Can I pass the state readMore as a prop of the component ReadMore ? Thank you !
import React, { useState } from 'react';
import '../style/catalogue.scss';
import collectionsItems from '../Components/collectionsItemsData';
import { Link } from "react-router-dom";
const HomeButtons = ({}) => {
function ReadMore() {
const [readMore, setReadMore] = useState(false)
function toggleSetReadMore() {
setReadMore(!readMore)
}
return (
<p className='showmore' onClick={toggleSetReadMore} className={readMore ? "collection-item active" : "collection-item"}>TOGGLE BUTTON</p>
)
}
return <div>
{collectionsItems.map((collectionItem) => {
const { id, category, img } = collectionItem;
return < article key={id} >
<img className="item-img" src={img} alt=''/>
<ReadMore />
<Link to={`/${category}`} className="item-title">{category}</Link>
</article>
})}
</div>
}
export default HomeButtons;
First of all you need extract ReadMore component from function outside!
And for your problem you can lift state up(https://reactjs.org/docs/lifting-state-up.html). And since at the same time only one item can be opened you can do something like this:
function ReadMore({ isOpened, setOpened }) {
return (
<p
onClick={setOpened}
className={isOpened ? "collection-item active" : "collection-item"}
>
TOGGLE BUTTON
</p>
);
}
const HomeButtons = () => {
const [openedItemId, setOpenedItemId] = useState(null);
return (
<div>
{collectionsItems.map((collectionItem) => {
const { id, category, img } = collectionItem;
return (
<article key={id}>
<img className="item-img" src={img} alt="" />
<ReadMore
isOpened={openedItemId === id}
setOpened={() => setOpenedItemId(id)}
/>
<Link to={`/${category}`} className="item-title">
{category}
</Link>
</article>
);
})}
</div>
);
};

React useEffect Problems

So here is the problem which I can't seem to solve. I have an app component, inside of App I have rendered the Show Component. Show component has toggle functionality as well as a outside Click Logic. In the Show component I have a Button which removes an item based on his Id, problem is that When I click on the button Remove. It removes the item but it also closes the Show Component, I don't want that, I want when I press on button it removes the item but does not close the component. Thanks
App.js
const App =()=>{
const[isShowlOpen, setIsShowOpen]=React.useState(false)
const Show = useRef(null)
function openShow(){
setIsShowOpen(true)
}
function closeShowl(){
setIsShowOpen(false)
}
const handleShow =(e)=>{
if(show.current&& !showl.current.contains(e.target)){
closeShow()
}
}
useEffect(()=>{
document.addEventListener('click',handleShow)
return () =>{
document.removeEventListener('click', handleShow)
}
},[])
return (
<div>
<div ref={show}>
<img className='taskbar__iconsRight' onClick={() =>
setIsShowOpen(!isShowOpen)}
src="https://winaero.com/blog/wp-content/uploads/2017/07/Control-
-icon.png"/>
{isShowOpen ? <Show closeShow={closeShow} />: null}
</div>
)
}
Show Component
import React, { useContext } from 'react'
import './Show.css'
import { useGlobalContext } from '../../context'
import WindowsIcons from '../../WindowsIcons/WindowsIcons'
import { GrClose } from 'react-icons/gr'
const Show = ({closeShow}) => {
const {remove, icons }= useGlobalContext()
}
return (
<div className='control__Panel'>
<div className='close__cont'>
<GrClose className='close' onClick={closeShow} />
<h3>Show</h3>
</div>
<div className='control__cont'>
{icons.map((unin)=>{
const { name, img, id} = unin
return (
<li className='control' key ={id}>
<div className='img__text'>
<img className='control__Img' src={img} />
<h4 className='control__name'>{name}</h4>
</div>
<button className='unin__button' onClick={() => remove(id)} >remove</button>
</li> )
})}
</div>
</div>
)
}
export default Show
Try stop propagation function, it should stop the propagation of the click event
<button
className='unin__button'
onClick={(e) => {
e.stopPropagation();
remove(id);
}}
>remove</button>
You have a few typos in your example. Are they in your code? If they are, you're always reach the closeShow() case in your handler, since you're using the wrong ref.
const App =()=>{
const[isShowOpen, setIsShowOpen]=React.useState(false) <<-- Here 'isShowlOpen'
const show = useRef(null) <<-- here 'S'how
function openShow(){
setIsShowOpen(true)
}
function closeShow(){ <<-- Here 'closeShowl'
setIsShowOpen(false)
}
const handleShow =(e)=>{
if(show.current&& !show.current.contains(e.target)){ <<-- here 'showl'
closeShow()
}
}
useEffect(()=>{
document.addEventListener('click',handleShow)
return () =>{
document.removeEventListener('click', handleShow)
}
},[])
return (
<div>
<div ref={show}>
<img className='taskbar__iconsRight' onClick={() =>
setIsShowOpen(!isShowOpen)}
src="https://winaero.com/blog/wp-content/uploads/2017/07/Control-
-icon.png"/>
{isShowOpen ? <Show closeShow={closeShow} />: null}
</div>
)
}

Why isn't useContext updating my value when imported in ReactJS?

I'm trying to use the createContext and useContext features of ReactJS to create a notification icon that displays a number of notifications increasing by 1 each second (essentially trying to figure out how to pass a state between files/components), but am unable to get the value to transfer over.
The timer appears to be working fine and the seconds variable in the timer file is definitely increasing, it's just the secs in the NavBar that isn't updating correctly.
--- App File ---
function App() {
return (
<div>
<NavBar />
<Timer />
</div>
);
}
export default App;
---Timer File---
...
export const secContext = createContext()
const Timer = () => {
const [seconds, setSeconds] = useState(0);
...
useEffect(() => {
...
if (isActive) {
interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);}
...
return (
...
<secContext.Provider value={seconds}>
<div className="time">
{seconds}s
</div>
...
</secContext.Provider>
...
);
};
---Navigation Bar File---
...
import {secContext} from './Timer'
export default function NavBar() {
const secs = useContext(secContext)
return (
...
<Badge badgeContent={secs}>
<NotificationsIcon />
</Badge>
...
);
}
I was expecting {secs} in the Navigation Bar file to update to be equal the value of the seconds value from the Timer, but instead it appears to remain null.
Here is a screenshot of the interface: https://gyazo.com/d283360091c9d4ea8d9b2785419ad665
In this case the notification icon should have a badge with the number 10.
Context values are only accessible if they are rendered within the hierarchy i.e.
<secContext.Provider value={x}>
<NavBar />
</secContext.Provider>
NavBar doesn't appear to be a descendant of your context, your context is created inside Timer and therefore is only accessible from descendants of that component e.g.
<Timer>
<NavBar />
</Timer>
Update
As per the comments discussion, if you simply want to share data between a couple of siblings, it would probably make more sense to just move the common up to the parent (App) and then pass the data into the siblings as props - see example.

No image uploaded "SRC" is undefined even with a check?

I'm facing a weird problem here I've created a check whether an image is uploaded or not. But for some reason, my "else" is not working.
Inside my main component "Fragrances" I'm looping through my API. And checking if the Array of images is empty return else show the image.
What am I doing wrong?
My code:
image component:
import React from 'react';
import NoPicture from 'components/NoPicture/NoPicture';
const Image = props => {
const { url } = props;
return url.length > 0 ? <img src={url} className="image" /> : <NoPicture />;
};
export default Image;
NoPicture component:
import React from 'react';
// No Picture
import NoPhotoImageURL from '../../images/no-photo.svg';
console.log(NoPhotoImageURL);
const NoPicture = () => (
<img
src={NoPhotoImageURL}
alt="No Photo"
className="image image--default"
/>
);
export default NoPicture;
Main component:
import React from 'react';
import { SITE_URL } from 'constants/import';
import Name from './name';
import Category from './category';
import Image from './image';
import Gallery from 'components/Gallery/gallery';
import Rating from './rating';
import Description from './description';
import Notes from './notes';
const Fragrances = props => {
const { FragranceData } = props;
return (
<section className="fragrances">
<div className="row">
{FragranceData.map(fragrance => {
console.log(fragrance);
const {
category,
description,
image,
gallery,
name,
rating,
notes,
Publish: isPublished,
} = fragrance;
const imageURL = image.path;
return isPublished ? (
<div key={fragrance._id} className="col-xs-12 col-sm-6">
<div className="fragrance">
<Name name={name} />
<Category category={category} />
<Image url={SITE_URL + imageURL} />
<Rating rating={rating} />
<Description description={description} />
<Notes notes={notes} />
<Gallery imageData={gallery} />
</div>
</div>
) : (
'Nothing published yet!'
);
})}
</div>
</section>
);
};
export default Fragrances;
Your question is not entirely clear on what exactly you are experiencing, but here is the most obvious problem in your code. You have this line in your Image component:
return url.length > 0 ? <img src={url} className="image" /> : <NoPicture />;
However, in your main component you are passing a concatenated string to the Image component:
<Image url={SITE_URL + imageURL} />
According to your comment, SITE_URL is the full URL, which will never be empty, so inside your Image component, url will always contain something, no matter what the value of imageURL is in the main component. Thus, url.length will always be greater than 0, and the img tag will render every time.
You will either need to pass the individual parts of the path down to the Image component separately, or move your check up into the main component.

Categories

Resources