Problem with setting state.index on click - javascript

I'm creating a webpage slide show. I created a file called SlideshowData.js where I exported an array of objects with all image links and ids. So using react I mapped through the photos and added dots to them. I created the dots and each time the photos switch the dot changes color from gray to black to indicate that the current photo is active.
The problem occurs now that I keep trying to figure out how to make them clickable. So for example you would click on the first dot it would bring you to the first slide. I tried to do it with a "set.state" function and set the initial index to the "event.target.key" which I assigned slide.id but it doesn't work.
Thank you for your time. I attached the code below.
class Slideshow extends React.Component{
constructor(props){
super(props);
this.state = {
index: 0,
delay: 5000,
length: SlideshowData.length,
}
this.clickedDot = this.clickedDot.bind(this)
}
componentDidMount(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
componentDidUpdate(){
document.addEventListener("onClick", this.clickedDot)
if(this.state.index === this.state.length -1){
setTimeout(()=> this.setState(()=>({
index: 0
})),this.state.delay)
}else{
setTimeout(()=> this.setState((state)=>({
index: state.index + 1,
})),this.state.delay)
}
}
clickedDot(){
this.setState((slide) =>({
index: this.state.length
}))
console.log(this.state.index)
}
render(){
return(
<div className="slidesContainer">
<div className="SlideshowSlider" style={{ transform: `translate3d(${-this.state.index * 100}%, 0, 0)` }}>
{SlideshowData.map((slide,index) => (
<img className="slides" src={slide.image} key={index} alt="travel"/>
))}
</div>
<div className = "slideshowDots">
{SlideshowData.map((slide,idx) => (
<div onClick={this.clickedDot} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} ></div>
))}
</div>
</div>
)
}
}
export default Slideshow

You can pass the index inside your onClick function on the dots such as this:
<div onClick={(idx) => this.clickedDot(idx)} key ={slide.id} className={`slideDot${slide.id === this.state.index ? " active" : ""}`} >
and then use the index to change the slide accordingly in your clickedDot function.

Related

Next JS custom carousel and looping/showing/hiding through items

I have a custom build Next JS carousel that keeps an index of the slide we are on and renders an image or video to the screen. It seems that because it is autoplaying and each slide gets removed and readded every 6 or so seconds the page downloads constant copies of the same video or image when it comes around again. Is this not the correct way of doing this?
So the important part is here
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
It will remove and readd content every slide. Does it waste resrouces constantly downloading them? Is there a better way?
import React from 'react'
//Importing data to use as the slides
import { slides } from './data/slides'
import VideoSlide from './VideoSlide'
import ImageSlide from './ImageSlide'
let slideTimer = null
class Carousel extends React.Component {
constructor(props) {
super(props)
this.state = {
currentImageIndex: 0, //Array index of slide from /data/slides
slideTime: 6, //Timing duration of a slide
}
this.setMyInterval = this.setMyInterval.bind(this)
}
//Runs when this componenet is included in the page
componentDidMount() {
this.setMyInterval()
}
changeSlide(current) {
/*Don't run if we are just clicking the same slide number*/
if (current != this.state.currentImageIndex) {
this.setState({ currentImageIndex: current }) //Change to selected slide1
clearTimeout(slideTimer) //Reset the timer so it's not half way through the countdown when we select another slide
this.setMyInterval() //Rebuild the slide countdown so we are starting at 0 and in sync with our CSS animation
}
}
setMyInterval() {
slideTimer = setInterval(() => {
const lastIndex = slides.length - 1 //Check when we need to loop
const { currentImageIndex } = this.state //Get current slide from state
const shouldResetIndex = currentImageIndex === lastIndex
const index = shouldResetIndex ? 0 : currentImageIndex + 1 //Reset to 0 if we are at the end
this.setState({
currentImageIndex: index, //Set new slide as number obtained from above
})
}, this.state.slideTime * 1000) //Repeat every x seconds
}
componentWillUnmount() {
clearInterval(slideTimer)
}
render() {
return (
<>
<div className="backgroundSlide">
{slides.map((item, key) => (
<>
{key == this.state.currentImageIndex && (
<div>
<VideoSlide url={slides[0].video} />
{slides[this.state.currentImageIndex].image && (
<ImageSlide
url={slides[this.state.currentImageIndex].image}
timer={this.state.slideTime}
/>
)}
</div>
)}
</>
))}
</div>
</>
)
}
}
export default Carousel
It's not clear from the question that what kind of Carousel logic you have. Usually, we render the whole carousel elements and then let the carousel do its job. As an example consider this CSS only carousel,
https://css-tricks.com/css-only-carousel/
If you use such an approach, you can have all of your slides rendered one time and don't have to worry about the removal/addition of any slides.

Div onClick function doesn't work when clicking in React app

I have a function which creates 2 divs when changing the number of items correspondingly (say if we choose 5 TVs we will get 5 divs for choosing options). They serve to make a choice - only one of two possible options should be chosen for every TV, so when we click on one of them, it should change its border and background color.
Now I want to create a dynamic stylization for these divs: when we click on them, they should get a new class (tv-option-active) to change their styles.
For that purposes I used 2 arrays (classesLess and classesOver), and every time we click on one of divs we should remove a class if it's already applied to the opposite option and push the class to the target element - thus only one of options will have tv-option-active class.
But when I click on a div I do not get anything - when I open the document in the browser and inspect the elements, the elements do not even receive new class on click - however, when I console log the classes variable that should apply to an element, it is the way it should be - "less tv-option-active" or "over tv-option-active". I applied join method to remove the comma.
I checked the name of imported css file and it is ok so the problem is not there, also I applied some rules just to make sure the problem is not there and it worked when it's not dynamic (I mean no clicks are needed).
So my list of reasons causing that trouble seems to be not working.
I also tried to reorganize the code in order to not call a function in render return - putting mapping directly to render return, but this also didn't work.
Can anyone give me a hint why it is that?
Here is my code.
import React from 'react'
import { NavLink, withRouter } from 'react-router-dom'
import './TVMonting.css'
import PageTitle from '../../PageTitle/PageTitle'
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
},
}
render() {
let classesLess = ['less']
let classesOver = ['over']
const tvHandlers = {
tvs: {
decrease: () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
},
increase: () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
},
},
}
const createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
return divsArray.map((i) => {
return (
<React.Fragment key={i}>
<div
className={classesLess.join(
' '
)}
onClick={() => {
const idx = classesOver.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesLess.splice(
idx,
1
)
}
classesLess.push(
'tv-option-active'
)
}}
>
Under 65
</div>
<div
className={classesOver.join(
' '
)}
onClick={() => {
const idx = classesLess.indexOf(
'tv-option-active'
)
if (idx !== -1) {
classesOver.splice(
idx,
1
)
}
classesOver.push(
'tv-option-active'
)
// classesOver.join(' ')
}}
>
Over 65
</div>
</React.Fragment>
)
})
}
return (
<div>
<button onClick={tvHandlers.tvs.decrease}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={tvHandlers.tvs.increase}>
+
</button>
{createDivs()}
</div>
)
}
}
export default withRouter(TVMontingRender)
CSS file is very simple - it just adds a border.
P.S. I know that with this architecture when I click on one of the divs all the divs will get tv-option-active class, but for now I just want to make sure that this architecture works - since I'm relatively new in React 🙂Thanks in advance!
Components won't have their lifecycle triggered if you are mutating a variable. You need a state for that purpose, which stores the handled data.
In your case you need some state to say which div has the active class, under or over. You can also abstract each rendered Tv to another Class component. This way you achieve independent elements that control their own class, rather than changing all others.
For that I created a Tv class, where I simplified some of the logic:
class Tv extends React.Component {
state = {
activeGroup: null
}
// this will update which group is active
changeActiveGroup = (activeGroup) => this.setState({activeGroup})
// activeClass will return 'tv-option-active' if that group is active
activeClass = (group) => (group === this.state.activeGroup ? 'tv-option-active' : '')
render () {
return (
<React.Fragment>
<div
className={`less ${ activeClass('under') }`}
onClick={() => changeActiveGroup('under')}
>
Under 65
</div>
<div
className={`over ${ activeClass('over') }`}
onClick={() => changeActiveGroup('over')}
>
Over 65
</div>
</React.Fragment>
)
}
}
Your TvMontingRender will be cleaner, also it's better to declare your methods at your class body rather than inside of render function:
class TVMontingRender extends React.Component {
state = {
tvData: {
tvs: 1,
under: 0,
over: 0,
}
}
decreaseTvs = () => {
if (this.state.tvData.tvs > 1) {
let tvData = {
...this.state.tvData,
}
tvData.tvs -= 1
this.setState({ tvData })
}
}
increaseTvs = () => {
if (this.state.tvData.tvs < 5) {
let tvData = {
...this.state.tvData,
}
tvData.tvs += 1
this.setState({ tvData })
}
}
createDivs = () => {
const divsNumber = this.state.tvData.tvs
let divsArray = []
for (let i = 0; i < divsNumber; i++) {
divsArray.push(i)
}
// it would be better that key would have an unique generated id (you could use uuid lib for that)
return divsArray.map((i) => <Tv key={i} />)
}
render() {
return (
<div>
<button onClick={this.decreaseTvs}>
-
</button>
{this.state.tvData.tvs === 1 ? (
<h1> {this.state.tvData.tvs} TV </h1>
) : (
<h1> {this.state.tvData.tvs} TVs </h1>
)}
<button onClick={this.increaseTvs}>
+
</button>
{this.createDivs()}
</div>
)
}
}
Note: I didn't change the key you are passing to Tv, but when handling an array that you manipulate somehow it's often better to pass an unique id identifier. There are some libs for that like uuid, nanoID.
When handling complex class logic, you may consider using libs like classnames, that would make your life easier.

React-Spring Parallax Can't Declare Offset With State Mapping Function

im trying to create a react page with react-spring's parallax.Im using web api for data so when i use parallax tags im trying to set offset and scrollTo function's value.As you can see below;
class HomeComponent extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
categoryCount: '',
}
}
componentDidMount() {
axios.get(`http://localhost:9091/api/category`)
.then(res => {
this.setState({ list: res.data, categoryCount: res.data.length })
});
}
so these are my declerations and web api call part, next part is render();
render() {
let i = 1
return <Parallax pages={this.state.categoryCount + 1} scrolling={true} vertical ref={ref => (this.parallax = ref)}>
<ParallaxLayer key={0} offset={0} speed={0.5}>
<span onClick={() => this.parallax.scrollTo(1)}>MAINPAGE</span>
</ParallaxLayer>
{this.state.liste.map((category) => {
return (
<ParallaxLayer key={category.categoryId} offset={i} speed={0.5}>
<span onClick={() => { this.parallax.scrollTo(i + 1) }}>{category.categoryName}</span>
{i += 1}
{console.log(i)}
</ParallaxLayer>
);
})}
</Parallax>
}
so in a part of this code, i am mapping the list for creating enough amount of parallax layer.But I can't manage the offset and this.parallax.scroll() 's values.These guys taking integer value for navigation to each other.
I tried the i and i+1 deal but it gets weird.First parallax works well it navigates the second page but after first page every page navigates me to the last page.I can't find a related question in stackoverflow so i need help on this one.Thanks for answers and sorry for my English.
After investigating the stackblitz, I see that the problem indeed was that the "i" value was increasing up to the list's length immediately, so wherever you clicked except for the first one, you were going to the last page.
I added a listIndex value to the map iteration, and incremented it there. You can follow the console.log statements, as well as the printed things on the screen.
This is a working solution but I'm more than certain there's a more elegant way to solve this (move it into a function etc).
render() {
let i = 1;
return <Parallax pages={this.state.liste.length + 1} scrolling={true} vertical ref={ref => (this.parallax = ref)}>
<ParallaxLayer key={0} offset={0} speed={0.5}>
<span onClick={() => this.parallax.scrollTo(1)}>MAINPAGE</span>
</ParallaxLayer>
{this.state.liste.map((category, listIndex) => {
return (
<ParallaxLayer key={category.categoryId} offset={listIndex + 1} speed={0.5}>
<span onClick={() => { this.parallax.scrollTo(listIndex + 1) }}>{category.categoryName} - test</span>
{listIndex += 1}
{console.log(listIndex)}
</ParallaxLayer>
);
})}
</Parallax>
}
Let me know if I can help with anything else.

Creating a button that fills in React

I'm new here and I have a question that I couldn't find answer to..
I am currently working on a website using ReactJS, and I want to have a button that fills itself whenever the user clicks on it. The button should have a total of 5 stages to it.
I am not asking for you to code it for me, but simply help me finding the best approach to this thing.
So what exactly am I asking? As you can see in this
It's a boxed element that whenever the user clicks on it (it can click on the whole element), the progress fills and it becomes something like this
So the first line is now marked. When the user presses on it again, the 2nd bar fills
Important - there will be text inside these bars that fills.
What have I done so far? I have been thinking of having 5 different images for every time the user presses on the element, but I was wondering if there might be a better approach to it (Like having the DIV background the image, and have sub-divs that fills up whenever the user presses... )
I hope I made myself clear, and thank you all for your time!
Here is a working example. You don't need an image for all of the different states. It is far more flexible to do this dynamically with HTML.
The key to this is keeping track of the number of times the button has been clicked. In this example it uses currentState to keep track of how many times it has been clicked.
const defaultStyle = {
width: 100,
padding: 5,
};
class MultiLevelButton extends React.Component {
constructor(props) {
super(props);
this.state = {
currentState: 0,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { currentState } = this.state;
if (currentState < this.props.states.length) {
this.setState({
currentState: currentState + 1,
});
}
}
reset() {
this.setState({
currentState: 0,
});
}
render() {
const { currentState } = this.state;
const { states } = this.props;
return (
<button onClick={this.handleClick} style={{border: 'none', outline: 'none'}}>
{
states
.map((s, i) => {
const stateNumber = states.length - i;
const overrides = stateNumber <= currentState ? { backgroundColor: '#000', color: '#fff' } : {};
const style = {
...defaultStyle,
backgroundColor: s,
...overrides,
};
return <div style={{...style}}>{stateNumber}</div>
})
}
</button>
)
}
}
const buttonRef = React.createRef();
ReactDOM.render(
<div>
<MultiLevelButton ref={buttonRef} states={['#bbb', '#ccc', '#ddd', '#eee', '#fff']} />
<MultiLevelButton states={['#fcc', '#cfc', '#ccf']} />
<div>
<button onClick={() => buttonRef.current.reset()}>Reset</button>
</div>
</div>,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
As you are using react. use create step/level as component and you will pass props of styles. you can map that component 5 times or n times depending upon requirement. The view you have shown no need images use css to achieve it.
change props of component when user click on it.
You can use state in order to keep the click count and change the button background on the basis of click count.
const colors = ["#dfddc7", "#f58b54", "#a34a28", "#211717"]; //color array
class App extends Component {
constructor(props) {
super(props);
this.state = {
index : 0
}
}
handleChange() { // function will be called whenever we click on button
let {index} = this.state;
if (index >= 5) {
return; // you don't want to change color after count 5
}
index++;
console.log(index);
this.setState({index})
}
render() {
const {index} = this.state;
return (
<div className="App">
<button style = {{background:colors[index]}} //we are setting dynamic color from array on the basis of index
onClick = {this.handleChange.bind(this)}> click to change images
</button>
</div>
);
}
}
You can place <div></div> inside a button with different background color instead of images.
In the following example, I hold the number of clicks in the state. By comparing this value with the index of the step, you can see if it needs to be green or transparent
const numberOfSteps = 5;
class App extends React.Component {
state = {
numberOfClicks: 0
};
handleClick = e => {
this.setState({
numberOfClicks: (this.state.numberOfClicks + 1) % (numberOfSteps + 1)
}); // Use module (%) to reset the counter after 5 clicks
};
render() {
const { numberOfClicks } = this.state;
const steps = Array(numberOfSteps)
.fill()
.map((v, i) => i)
.map((i, index) => {
const color = numberOfClicks >= index + 1 ? "limegreen" : "transparent";
return (
<div
style={{
backgroundColor: color,
height: "30px",
border: ".5px solid gray"
}}
>
Bar {index + 1}
</div>
);
});
return (
<button
className="button"
style={{ height: "200px", width: "200px", backgroundColor: "lightgreen" }}
onClick={this.handleClick}
>
{steps}
</button>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
The key concept is state. When you click your button you should set some state, and when you render the button you should render it based on the state.
Here's a simple example where I render a button which contains 5 div elements that are filled (by setting backgroundColor style property) based on the state.
class Example extends Component {
constructor(props) {
super(props);
this.state = {
buttonState: 0,
};
}
onClick = () => {
let buttonState = this.state.buttonState;
buttonState++;
if(buttonState > 4) buttonState = 0; // wrap around from 4 - 0
this.setState({buttonState: buttonState});
}
// render a button element with some text, and a background color based on whether filled is true/false
renderButtonElement(elementText, filled) {
const backgroundStyle = filled ? {backgroundColor: 'green'} : {backgroundColor: 'white'};
const textStyle = {color: 'grey'};
return(
<div style={[backgroundStyle, textStyle]}>
<div>{elementText}</div>
</div>
);
}
render() {
return(
<button
onClick={this.onClick}
>
{/* make a temporary array of 5 elements, map over them and render an element for each one */}
{Array(5).fill().map((_, i) => this.renderButtonElement(i + 1, i <= this.state.buttonState))}
</button>
);
}
}

ReactJS onClick .next() element with same class?

I am new to ReactJS and I was wondering what is the correct way to target next element with same class in react?
<div className="portfolioGallery">
<img className="portfolioImg activeImg" src="img/1.png"/>
<img className="portfolioImg" src="img/2.png"/>
<img className="portfolioImg" src="img/2.png"/>
<div className="portfolioNext" onClick={this.nextImg.bind(this)}>
Next image
</div>
</div>
What would be the correct way that when I click the portfolioNext div I would be able to give the img2 class of activeImg and remove it from the previous element and so on in ReactJS?
Thank You!
constructor() {
super();
this.state = {
default: "portfolioImg activeImg"
};
}
nextImg() {
this.setState({
default: "portfolioImg"
});
}
That's the kind of imperative technique that you'd generally find in jQuery code, but it doesn't map very well to React's slightly more declarative nature.
Rather than trying to find the next element with a class, use state to maintain a list of those elements alongside an index cursor.
// constructor
this.state = {
images = ['img/1.png', 'img/2.png', 'img/3.png']
cursor: 0
};
Then use these bits of data to render your view.
// render
const { images, cursor } = this.state;
return (
<div>
{images.map((src, index) => {
const activeClass = (index === cursor) ? 'activeImg' : '';
return <img className={`portfolioImg ${activeClass}`} />;
}}
</div>
);
To change the active image, use setState to change the cursor property.
// nextImg
const { cursor, images } = this.state;
const nextCursor = cursor % images.length;
this.setState({ cursor: nextCursor });
I wouldn't suggest you think of it as siblings finding each other, but instead thing of it as the parent storing an index of the current children, and updating that instead.
this.props (or this.state) would have something like this (pseudocode)
this.props.images => ["img/1.png", "img/2.png", "img/2.png"];
Inside render:
<div className="portfolioGallery">
{this.props.images.map((image, i ) => active === i ? (<img className="portfolioImg activeImg" src="image" key={i}/>) : (<img className="portfolioImg " src="image" key={i}/>))}
<button className="portfolioNext" onClick={(e) => this.setState({active: this.state.active + 1}).bind(this)}>Next image</button>
</div>
Of course, accounting for when active >= images.length, but you get the idea

Categories