Sort movies with React JS

In this example below you will see how to do a Sort movies with React JS with some HTML / CSS and Javascript

Sort movies by rating and by title in ascending and descending order

Thumbnail
This awesome code was written by -J0hn-, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright -J0hn- ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Sort movies with React JS</title>
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div id="root"></div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/-J0hn-/sort-movies-with-react-js-MEpavZ */
img {
  width: 100%;
}

form {
  padding: 10px;
  display: flex;
  justify-content: flex-end;
}
form input[type="submit"] {
  border: none;
  background: orangered;
  color: white;
  margin-left: 15px;
  border-radius: 3px;
  padding: 0 15px;
  cursor: pointer;
}

#rating-filter {
  color: white;
  padding: 5px;
  background: orangered;
  border: none;
  cursor: pointer;
}

section {
  margin: auto;
  margin-top: 20px;
  max-width: 760px;
  display: flex;
  flex-wrap: wrap;
}

figure {
  background-color: white;
  width: 14em;
  margin: .50em;
  box-shadow: 0 5px 18px 0 gray;
  overflow: hidden;
  position: relative;
}
figure img {
  height: 21em;
}
figure figcaption {
  line-height: 2;
  padding: 0 .80em;
}
figure figcaption p {
  text-transform: capitalize;
  font-size: .80em;
  margin-bottom: 0;
  margin-top: 0;
  color: orangered;
}
figure figcaption .rating {
  display: flex;
  align-items: center;
}
figure figcaption .rating .fa-heart {
  color: #fa5050;
  margin: .50em .50em .50em 0;
}
figure figcaption .rating h4 {
  margin: 0;
}

@media (max-width: 737px) {
  section {
    justify-content: center;
  }
}


/*Downloaded from https://www.codeseek.co/-J0hn-/sort-movies-with-react-js-MEpavZ */
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var movies = [{
  title: "Mad Max: Fury Road",
  genre: ["Action", "Adventure", "Sci-Fi"],
  rating: 8.3,
  poster: "https://s-media-cache-ak0.pinimg.com/originals/ce/0c/93/ce0c93d50ae68922d1f4f6667c95e1a8.jpg"
}, {
  title: "The Hunger Games: Mockingjay Part 1",
  genre: ["Adventure", "Sci-Fi", "Thriller"],
  rating: 6.8,
  poster: "https://1.bp.blogspot.com/-Ds0sudZmSq4/Vgxrr75E77I/AAAAAAAAREo/sZkZW5YMDTw/s1600/Mockingjay%2BPart%2B1.jpg"
}, {
  title: "Jurassic World",
  genre: ["Action", "Adventure", "Sci-Fi"],
  rating: 7.2,
  poster: "https://s-media-cache-ak0.pinimg.com/736x/0b/ab/9a/0bab9a9c671dbb7aa8626eec44a0195f.jpg"
}, {
  title: "Everest",
  genre: ["Adventure", "Drama", "Thriller"],
  rating: 7.4,
  poster: "http://www.impawards.com/2015/posters/everest_ver4.jpg"
}, {
  title: "Insurgent",
  genre: ["Adventure", "Sci-Fi", "Thriller"],
  rating: 6.4,
  poster: "http://cdn2-www.comingsoon.net/assets/uploads/2015/01/FIN16_Insurgent_Guns_1Sht_Trim-1422379653-mtv-14224534611.jpg"
}, {
  title: "Sicario",
  genre: ["Action", "Crime", "Drama"],
  rating: 7.6,
  poster: "https://s-media-cache-ak0.pinimg.com/564x/7f/a1/5c/7fa15c26aa2cb48562ea37bbc177be74.jpg"
}, {
  title: "Green Lantern",
  genre: ["Action", "Adventure", "Sci-Fi"],
  rating: 5.6,
  poster: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTMyMTg3OTM5Ml5BMl5BanBnXkFtZTcwNzczMjEyNQ@@._V1_UX182_CR0,0,182,268_AL_.jpg"
}, {
  title: "Prisoners",
  genre: ["Crime", "Drama", "Mystery"],
  rating: 8.1,
  poster: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0NTIzMjQ1NV5BMl5BanBnXkFtZTcwNDc3MzM5OQ@@._V1_UX182_CR0,0,182,268_AL_.jpg"
}, {
  title: "The Hateful Eight",
  genre: ["Crime", "Drama", "Mystery"],
  rating: 7.8,
  poster: "https://images-na.ssl-images-amazon.com/images/M/MV5BMjA1MTc1NTg5NV5BMl5BanBnXkFtZTgwOTM2MDEzNzE@._V1_UX182_CR0,0,182,268_AL_.jpg"
}];

// flatten movies.genre array
// const genres = movies
// .map(m => m.genre)
// .reduce((acc, val) => acc.concat(val), [])
// .filter((elem, index, arr) => index === arr.indexOf(elem))


// removes all articles in the movie title
function strip(title) {
  return title.replace(/^(a|an|the)\s/i, "");
}

var App = function (_React$Component) {
  _inherits(App, _React$Component);

  function App(props) {
    _classCallCheck(this, App);

    var _this = _possibleConstructorReturn(this, (App.__proto__ || Object.getPrototypeOf(App)).call(this, props));

    _this.handleChange = function (e) {
      _this.setState({ value: e.target.value });
    };

    _this.handleSubmit = function (e) {
      var _this$state = _this.state,
          value = _this$state.value,
          movies = _this$state.movies;


      switch (value) {
        case "Low rating":
          _this.setState({
            movies: movies.sort(function (a, b) {
              return a.rating > b.rating ? 1 : -1;
            })
          });
          break;
        case "High rating":
          _this.setState({
            movies: movies.sort(function (a, b) {
              return b.rating > a.rating ? 1 : -1;
            })
          });
          break;
        case "A-Z":
          _this.setState({
            movies: movies.sort(function (a, b) {
              return strip(a.title) > strip(b.title) ? 1 : -1;
            })
          });
          break;
        case "Z-A":
          _this.setState({
            movies: movies.sort(function (a, b) {
              return strip(b.title) > strip(a.title) ? 1 : -1;
            })
          });
          break;
        default:
          _this.setState({
            movies: movies
          });
          break;

      }

      e.preventDefault();
    };

    _this.state = {
      movies: movies,
      value: "Sort"
    };

    return _this;
  }

  _createClass(App, [{
    key: "render",
    value: function render() {
      var _state = this.state,
          movies = _state.movies,
          value = _state.value;

      return React.createElement(
        "div",
        null,
        React.createElement(
          "form",
          { onSubmit: this.handleSubmit },
          React.createElement(
            "select",
            { id: "rating-filter", value: value, onChange: this.handleChange },
            React.createElement(
              "option",
              { value: "Sort" },
              "Sort"
            ),
            React.createElement(
              "option",
              { value: "Low rating" },
              "Low rating"
            ),
            React.createElement(
              "option",
              { value: "High rating" },
              "High rating"
            ),
            React.createElement(
              "option",
              { value: "A-Z" },
              "A-Z"
            ),
            React.createElement(
              "option",
              { value: "Z-A" },
              "Z-A"
            )
          ),
          React.createElement("input", { type: "submit", value: "Filter" })
        ),
        React.createElement(
          "section",
          null,
          movies.map(function (m) {
            return React.createElement(Movietemplate, { movie: m });
          })
        )
      );
    }
  }]);

  return App;
}(React.Component);

var Movietemplate = function (_React$Component2) {
  _inherits(Movietemplate, _React$Component2);

  function Movietemplate(props) {
    _classCallCheck(this, Movietemplate);

    return _possibleConstructorReturn(this, (Movietemplate.__proto__ || Object.getPrototypeOf(Movietemplate)).call(this, props));
  }

  _createClass(Movietemplate, [{
    key: "render",
    value: function render() {
      var _props$movie = this.props.movie,
          genre = _props$movie.genre,
          rating = _props$movie.rating,
          poster = _props$movie.poster;

      return React.createElement(
        "figure",
        null,
        React.createElement("img", { src: poster }),
        React.createElement(
          "figcaption",
          null,
          React.createElement(
            "p",
            null,
            genre.join(' ')
          ),
          React.createElement(
            "div",
            { className: "rating" },
            React.createElement("i", { className: "fa fa-heart" }),
            React.createElement(
              "h4",
              null,
              rating
            )
          )
        )
      );
    }
  }]);

  return Movietemplate;
}(React.Component);

ReactDOM.render(React.createElement(App, null), document.getElementById("root"));

Comments