how to use onClick in react slick - javascript

I am using react slick in my Websites. I have 4 slides. Every Slide, I want a onClick Function to get the value. But When I click on the Slide, I am getting the last value only. I searched Stack Overflow but can't find solutions.
Here's the Code:
const productSlideImg = [
{ Img: prodImg1, ImgName: "img1", pageLink: "/home" },
{ Img: prodImg2, ImgName: "img2", pageLink: "/about" },
{ Img: prodImg3, ImgName: "img3", pageLink: "/contact" }
];
const handleClickSlide = (item) => {
console.log(item); // getting "img3" only on every slide click
};
<Slider
autoplay={true}
slidesToShow={1}
slidesToScroll={1} >
{productSlideImg.map((item, index) => (
<div >
<img
style={{ borderRadius: "50px" }}
width={"100%"}
src={item.Img}
onClick={() => {handleClickSlide(item.ImgName) }}
/>
</div>
))}
</Slider>
Please help me with some solutions

you have created a different function handleClickProduts
and using different function on img onClick
onClick={() => {handleClickProduts (item.ImgName) }}
CodeBox link: working code

Related

I getting this error 'Uncaught Error: Objects are not valid as a React child' even if I used Array of objects what to do

`
const fashionCardData = [
{ id: "1", src: "1.png" },
{ id: "2", src: "2.png" },
{ id: "4", src: "4.png" },
];
const Products = () => {
return (
<Box>
{fashionCardData.map((item)=>{
<img key={item.id} src={`images/${item.src}`} alt={item.id}/>
})}
</Box>
);
};
`
I am trying to map an array but it doesn't work please help
Replace
{fashionCardData.map((item)=>{
<img key={item.id} src={`images/${item.src}`} alt={item.id}/>
})}
with
{fashionCardData.map((item)=>(
<img key={item.id} src={`images/${item.src}`} alt={item.id}/>
))}
Problem is you are not returning the component.
Change your code to
{fashionCardData.map((item)=>{
return (<img key={item.id} src={`images/${item.src}`} alt={item.id}/>);
})}
Code that is inside {} will be treated as javascript and similarly code that is inside () will be treated as jsx.

showing only first element from data

Hi all I have following code: my code
In this scenario I am receiving some data from backend
const attachments = [
{
id: 1,
name: "someURLL_Name_1",
link: "https://someURLL_Name_1",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
},
{
id: 2,
name: "someURLL_Name_2",
link: "https://someURLL_Name_2",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
},
{
id: 3,
name: "someURL_Name_3",
link: "https://someURLL_Name_3",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
}
];
I need to map them all and show only first element form my data, and show with numbers rest hided data.
In the end it should be like something like this:
someURL_Name_1 https://someURLL_Name_1 +2 more
I successfully mapped all my data and write little logic for + more.
<div className={Styles.attachments}>
{data.map((item) => {
return <Attachment key={item.id} data={item} image={item.img} />;
})}
{data.length > 1 && (
<span className={Styles.more}>+{data.length - 1} more</span>
)}
</div>
Please help me to resolve a problem. Again, I want to show only first element , and then if there are another elements then I should hide them and show hide elements with numbers.
Thanks.
Just don't map over all entries then. The following will work :-
export const Attachments = ({ data }) => {
return (
<div className={Styles.attachments}>
{data[0] && (
<Attachment key={data[0].id} data={data[0]} image={data[0].img} />
)}
{data.length > 1 && (
<span className={Styles.more}>+{data.length - 1} more</span>
)}
</div>
);
};

How can I add descriptions to my slideshow?

I am working on a web app in the ReactJS framework and I'm using react-slideshow-image component for a simple slideshow. However due to how the component works, I can only render the images. I would like to add a short description for each image and have it appear with it. Is there a way to modify this code to render a description under the image? (I was thinking about useEffect hook but I'm not sure.)
const Slideshow = () => {
return (
<SlideContainer>
//styled component
<Zoom scale={0.4}>
//Zoom component comes from react-slideshow-image
{
slideshowImages.map((each, index) => <img key={index} style={{padding: "0", margin: "0", width: "20vw"}} src={each} />)
}
</Zoom>
</SlideContainer>
)
};
Try this behavior, Here you can show the description on the image.
const images = [
{
id: "img1",
url: "../images/image-1.png",
description: "image 1 description here"
},
{
id: "img2",
url: "../images/image-2.png",
description: "image 2 description here"
}
];
const Slideshow = () => {
return (
<div className="slide-container">
<Zoom {...zoomOutProperties}>
{images.map((each, index) => (
<div
style={{
background: `url(${each.url}) no-repeat`,
width: "300px",
height: "240px"
}}
>
<b>{each.description}</b>
</div>
))}
</Zoom>
</div>
);
};
Hope you are looking for the same use case.
Working demo:- https://codesandbox.io/s/modest-proskuriakova-28qsk?file=/src/App.js
This wasn't quite what I wanted but it pointed me in the right direction. Here's my solution inspired by yours and official React documentation:
const slideshowImages = [
{
id: 1,
image: "/imageUrl",
desc: //description
},
//as many elements as you want
]
const Slideshow = () => {
//SlideContainer and DescriptionWrapper are styled components
return (
<SlideContainer>
<Zoom {...zoomOutProperties}>
{
slideshowImages.map(
(slide) =>
<div key={slide.id}>
<img style={{padding: "0", margin: "0", width: "20vw"}} src={slide.image} />
<DescriptionWrapper>{slide.desc}</DescriptionWrapper>
</div>
)
}
</Zoom>
</SlideContainer>
)
};
export default Slideshow;
Thanks a lot, I wouldn't have thought of something like this.

Change image onClick in React Js

I'm trying to create a page in my React Js project, with the content on the left side and content's image on the right side. So far, I was able to create a toggle function that changes text and image according to the selected title, so, for example, if a user clicks title 1, text1 & image1 will be displayed, and when the user clicks title2, text2 & image2 will be rendered and etc. The problem is that images don't load until a title was clicked, but I need to display img1 when page loads for the first time(and then img1 should change to img2 or img3, depending on the clicked title).
codesandbox
My code:
import React, { useState } from "react";
import "./styles.css";
const data = [
{
id: "1",
key: "1",
title: "Title1",
text: "Text1.",
img: "1.jpg"
},
{
id: "2",
key: "2",
title: "Title2",
text: "Text2.",
img: "2.jpg"
},
{
id: "3",
key: "3",
title: "Title3",
text: "Text3.",
img: "3.jpg"
},
{
id: "4",
key: "4",
title: "Title4",
text: "Text4",
img: "4.jpg"
}
];
export default function App() {
const [toggled, toggle] = useState("");
return (
<div className="App">
{data.map(({ title, text, key, img }) => {
return (
<>
<div className="main">
<div className="text">
<h1 onClick={() => toggle(key)}>{title} </h1>
{toggled === key ? (
<>
<p>{text}</p>
</>
) : null}
</div>
<div className="img">
{toggled === key ? (
<>
<img src={img} key={key} className="photo" />
</>
) : null}
</div>
</div>
</>
);
})}
</div>
);
}
This is how the page is displaying on load now
This is how I want the page to be on load(with img1 being displayed)
What I would love to do is when the page is loaded, it should display img1, but when the user clicks title2, img1 should change to img2, any suggestions will be greatly appreciated,
Thank you.
I did a bit of refactoring for you, try this: https://codesandbox.io/s/toggle-kc3q2
I set the initial state to be "1" and using toggle and setToggle as the state and state setter
I'm posting my solution here, in case anyone else stumbles upon a similar problem. I added the following lines of code to my project:
***const [visible, setVisible] = useState(true);***
<h1 onClick={() => {
setToggle(key);
***setVisible(false);***
}}>
<div className="img">
***{visible && key === "1" ? (
<img src={img}
key={key}
/>)
: null}***
</div>
codesandbox
In this case, when the page is loaded, it displays img1 and only titles(without their texts), and only when a user clicks any title, a text, and its image is displayed.

React, update array's total count state when new item is added to it

I have my array where you can add a "player" to it and it updates just fine. I also have a total number of players that looks at the array and gives the total sum. It works but it does not factor in the new items.
I know I need to pass it the new updated state of the array (players) but I'm just stuck on how to do that.
I've provided snips of my code as follows
Array
const players = [
{
name: 'Jabba',
score: 10,
id: 11
},
{
name: 'Han',
id: 1
},
{
name: 'Luke',
id: 2
},
Function to add to the array
handleChange = e => {
this.setState({
newPlayerName: e.target.value
});
};
handleAddPlayer = e => {
this.setState(prevState => ({
players: [
...prevState.players,
{
name: this.state.newPlayerName,
id: getRandomInt(20, 155)
}
]
}));
};
my state
this.state = {
id: players.id,
totalScore: 0,
totalPlayers: players,
countInfo: [],
evilName: '',
color: '#6E68C5',
scoreColor: '#74D8FF',
fontAwe: 'score-icon',
incrementcolor: '',
scoreNameColor: 'white',
glow: '',
buttonStyle: 'count-button-start',
newPlayerName: '',
max_chars: 15,
chars_left: '',
players
};
And finally the function that should update the total but doesn't and where I'm stuck
function Stats(props) {
const totalPlayers = props.players.length;
const totalScore = props.players.reduce(
function(total, player) {
return props.totalScore + props.totalScore;
},
0
);
return (
<div style={{ width: '100%' }}>
<PlayerNumb>Number of players: <b>{totalPlayers}</b></PlayerNumb>
</div>
);
}
the const totalPlayers = props.players.length; is where I seemed to be tripped up. Any help would be greatly appreciated and apologies if I gave any confusing information as React is still new to me.
Also an example of how I called stats:
<Stats
style={{ width: '100%' }}
totalScore={this.state.totalScore}
players={players}
/>
And the complete render code of how Players is created
render() {
const listPlayers = this.state.players.map(player => (
<Counter
key={player.id}
player={player}
playersArray={this.state.players}
name={player.name}
sortableGroupDecorator={this.sortableGroupDecorator}
decrementCountTotal={this.decrementCountTotal}
incrementCountTotal={this.incrementCountTotal}
removePlayer={this.removePlayer.bind(this)} //bind this to stay in the context of the parent component
handleClick={player}
/>
));
return (
<ContainLeft style={{ alignItems: 'center' }}>
<ProjectTitle>Score Keeper</ProjectTitle>
<Copy>
A sortable list of players that with adjustable scores. Warning, don't go negative!
</Copy>
<GroupHolder>
<Stats
style={{ width: '100%' }}
totalScore={this.state.totalScore}
players={players}
/>
<div
style={{ width: '100%' }}
className="container"
ref={this.sortableContainersDecorator}
>
<div className="group">
<div className="group-list" ref={this.sortableGroupDecorator}>
{listPlayers}
</div>
</div>
</div>
<HandleForm>
<form
style={{ width: '100%' }}
onSubmit={this.handleClick.bind(this)}
>
<p className="sort-player">Add A Player</p>
<InputText
type="text"
maxLength="15"
max="4"
name="usr"
placeholder="Enter a new name"
value={this.state.newPlayerName}
onChange={this.handleChange}
/>
<PlayerButton onClick={this.handleAddPlayer}>
Press to Add Player
</PlayerButton>
<CharacterCount>
Characters left
{' '}
{this.state.max_chars - this.state.newPlayerName.length}
</CharacterCount>
</form>
</HandleForm>
</GroupHolder>
</ContainLeft>
);
}
}
export default Container;
You're calling your render function with an undefined variable called players
players={players}
You either need to pass this.state.players or define it with const players = this.state.players;
You should always be developing locally with an eslint plugin for your editor, which will highlight problems like these as syntax errors and save you hours of time.

Categories