Reputation: 141
I am new to React. I have implemented the following code for an assignment have. The goal is to get the list of the movies and when click on a movie to show the opening crawl. I decided to use two components for that because of the styling that had to be done(movies on the left ,crawl on the right).
Now I need two more options: Sort the movies by year or by id and to filter with a search bar above.
How can that be done in the component?
Here is my code:
import React, { Component } from 'react';
import './App.css';
class StarWarsApp extends React.Component{
constructor(props){
super(props);
this.handleSort = this.handleSort.bind(this);
this.handleMovies = this.handleMovies.bind(this);
this.handleClick = this.handleClick.bind(this);
this.state = {
movies: [],
crawl: ['No movie selected']
}
this.handleMovies();
}
handleMovies(){
fetch('"https://swapi.co/api/films"').then(results => {
return results.json();
}).then(data => {
let movies = data.results;
console.log(movies);
this.setState(() => {
return{
movies: movies
}
})
})
}
handleClick(event){
fetch('https://swapi.co/api/films'+event.currentTarget.id).then(results => {
return results.json();
}).then(data => {
let crawl = data.results.opening_crawl;
this.setState(() => {
return{
crawl:crawl
}
})
})
}
render(){
const title = 'Star Wars';
return(
<div>
<Header title={title}/>
<Sort handleSort={this.handleSort}/>
<Movies handleClick={this.handleClick} movies={this.state.movies}/>
<Crawl crawl={this.state.crawl}/>
</div>
)
}
}
class Header extends React.Component{
render(){
return(
<div>
<h1>{this.props.title}</h1>
</div>
)
}
}
class Movies extends React.Component{
render(){
return(
this.props.movies.map((movie) =>
<div onClick={this.props.handleClick} id={movie.episode_id} key={movie.episode_id}>
{
<p><Movie title={movie.title}/></p>
}
</div>
)
)
}
}
class Movie extends React.Component{
render(){
return(
<div>{this.props.title}</div>
)
}
}
class Crawl extends React.Component{
render(){
return(
<div className="split right">
{this.props.crawl}
</div>
)
}
}
export default StarWarsApp;
Upvotes: 1
Views: 2010
Reputation: 2212
Your handlesort function should be something like that:
handleSort = () => {
let copyOfMovies = this.state.movies.slice();
const sortedMovies = movies.sort((a,b) => {
const nameA = a.name.toUpperCase(); // ignore upper and lowercase
const nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
this.setState({movies:sortedMovies})
}
Upvotes: 2