_vksgg
Last Updated: January 25, 2019
·
133
· techmsi

Slideshow

Data

const slideshow = [
"https://loremflickr.com/320/240/paris?lock=1",
"https://loremflickr.com/320/240/paris?lock=2",
"https://loremflickr.com/320/240/paris?lock=3"
];

Styles

* {
  box-sizing: border-box;
}
body {
  font-family: sans-serif;
  background: tomato;
}
button {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 2rem;
  vertical-align: middle;
}
img {
  max-width: 100%;
}
:disabled {
  opacity: 0.4;
}
/* Slideshow */
.slideshow {
  width: 100%;
}
.slideshow > * {
  display: flex;
  justify-content: space-between;
}

.slides > * {
  display: none;
  border: 7px solid #fff;
}
.slides > *.active {
  display: block;
  animation: fade-in 1.5s cubic-bezier(0.39, 0.575, 0.565, 1) both;
}

@keyframes fade-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

Previous & Next buttons

const PrevNextNav = ({ step, totalSteps, setItem, children }) => {
  const prev = step => Math.max(0, step - 1);
  const next = step => Math.min(totalSteps, step + 1);

  return (
   <div>
      <button disabled={step === 0} onClick={() => setItem(prev(step))}> &laquo;</button>
      {children}
      <button disabled={step === totalSteps} onClick={() =>setItem(next(step))}>&raquo;</button>
    </div>
  );
};

App

class App extends Component {
  state = { currentSlide: 0 };

  setSlide = currentSlide => {
    this.setState({ currentSlide });
  };
  render() {
    const { currentSlide } = this.state;

    return (
      <div className="app">
        <div className="slideshow">
          <PrevNextNav
            totalSteps={slideshow.length - 1}
            setItem={this.setSlide}
            step={currentSlide}
          >
            <div className="slides">
              {slideshow.map((o, i) => (
                <img
                  className={`${i === currentSlide ? "active" : ""}`}
                  key={i}
                  src={o}
                />
              ))}
            </div>
          </PrevNextNav>
        </div>
      </div>
    );
  }
}