JSFiddle - React, Tailwind, and code Playground
by programko
HTML
<div id="app"></div>
CSS
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
box-sizing: border-box;
}
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
.dots {
display: flex;
justify-content: center;
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
.mySlides img {
width: 100%;
}
Babel + JSX
class Slider extends Component {
state = {
active: 0
};
componentDidMount() {
const { items } = this.props;
this.timeout = setTimeout(
() => this.updateActive(this.state.active, 1, items.length),
5000
);
}
componentDidUpdate(prevProps, prevState) {
const { items } = this.props;
const { active } = this.state;
if (
prevState.active !== active ||
prevProps.items.length !== items.length
) {
clearTimeout(this.timeout);
this.timeout = setTimeout(
() => this.updateActive(active, 1, items.length),
5000
);
}
}
componentWillUnmount() {
clearInterval(this.timeout);
}
updateActive = (active, step, length) => {
this.setState({
active: step ? (active + step + length) % length : active
});
};
next = e =>
this.setState({
active: this.updateActive(
this.state.active,
+e.target.dataset.step,
this.props.items.length
)
});
goTo = e => this.updateActive(+e.target.dataset.index);
render() {
const { active } = this.state;
const { items } = this.props;
const { length, [active]: slide } = items;
return (
<div>
<div className="slideshow-container">
<div className="mySlides fade">
<div className="numbertext">
{active + 1} / {length}
</div>
<img src={slide.img} />
<div className="text">{slide.title}</div>
</div>
<a className="prev" onClick={this.next} data-step={-1}>
❮
</a>
<a className="next" onClick={this.next} data-step={+1}>
❯
</a>
</div>
<div className="dots">
{items.map((n, i) => (
<span
key={n.id}
className={`dot ${i === active ? "active" : ""}`}
onClick={this.goTo}
data-index={i}
/>
))}
...