Reputation:
Today I'm working on a slideshow function. I just made a loop and I would like to style an element in the loop, but that went wrong.
slideshow.js:
import React from 'react';
let slideIndex = [1, 1];
let slideId = ["slide"];
showSlides(1, 0);
showSlides(1, 1);
function plusSlides(n, no) {
showSlides(slideIndex[no] += n, no);
}
function showSlides(n, no) {
let i;
let x = document.getElementsByClassName(slideId[no]);
if (n > x.length) {
slideIndex[no] = 1
}
if (n < 1) {
slideIndex[no] = x.length
}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex[no]-1].style.display = "block";
}
const SlideShow = (props) => {
return (
<div className={'slide'} style={{
display: 'none',
textAlign: 'center'
}}>
<img src={props.logo} className={'logo-banner'} style={{
verticalAlign: 'center'
}}/>
<a className={"prev-photo"} onClick={plusSlides(-1, 1)}>❮</a>
<a className={"next-photo"} onClick={plusSlides(1, 1)}>❯</a>
</div>
)
};
export default SlideShow;
My problem occured by line 22 and 24. because I gave it a style.display, but that doesn't work... has someone else a better solution. Please let me know!
Upvotes: 1
Views: 775
Reputation: 3026
You should avoid manipulating the DOM directly like this when using React. Doing so can interfere with React's Virtual DOM resulting in unexpected behaviour.
Instead, you could store the current slide in component state and control which slide is displayed that way.
Here's an example. You could control the slides in a higher order component instead and pass them through as props if you'd prefer.
class SlideShow extends React.Component {
constructor (props) {
super(props);
this.state = {
slides: ['slide-img01.png', 'slide-img02.png'],
currentSlideIndex: 0
};
}
handleNext () {
this.setState({
currentSlideIndex: this.state.currentSlideIndex + 1
});
}
handlePrev () {
this.setState({
currentSlideIndex: this.state.currentSlideIndex - 1
});
}
render () {
const { slides, currentSlideIndex } = this.state;
return (
<div className={'slide'}>
{slides.map((slide, index) =>
<img
key={index}
src={slide} className={'logo-banner'}
style={index === currentSlideIndex
? { verticalAlign: 'center' }
: { verticalAlign: 'center', display: 'none' }} />
)}
<a className={"prev-photo"} onClick={handlePrev.bind(this)}>❮</a>
<a className={"next-photo"} onClick={handleNext.bind(this)}>❯</a>
</div>
);
}
}
Upvotes: 1