George Katsanos George Katsanos - 19 days ago 5
Javascript Question

Should I use props or states in order to pass data?

I am fetching an array of items (call'em movies) from an API. Every movie has several details (title, director, cast, synopsis etc)

Here's a diagram of my structure:

components structure

Here is the MoviesList component :

constructor(props) {
super(props);

this.state = {
movies: []
};
}

componentDidMount() {
fetch('http://localhost:3335/movies')
.then(function(response) {
return response.json()
}).then((movies) => {
this.setState({ movies });
}).catch(function(ex) {
console.log('parsing failed', ex)
})
}

render() {
return (
<div className="movies">
<Movie movies={this.state.movies}></Movie>
</div>
);
}


And here is the movie:

render() {

const movielist = this.props.movies.map((movie) =>
<li>{movie.title}</li>
);

return (
<ul className="movie">
{ movielist }
</ul>
);

}


My questions:


  1. Should I use state or props to pass the data down from Movielist to Movie

  2. Since there's no "for" templating, how do I make it so I am not creating a list inside
    Movie
    but I am instead looping the entire
    Movie
    component inside
    Movielist
    ?



For example, I would like to achieve the following inside MovieList:

render() {
return (
<div className="movies">
<Movie for movie in movies></Movie>
</div>
);
}

Answer

render() of MovieList :

  render() {
    return (
      <div className="movies">
        {
          this.state.movies
          ? <ul>
              {this.state.movies.map((movie) => <Movie title={movie.title}/>)}
            </ul>
          : null
        }
      </div>
    );
  }

render() of Movie :

  render() {
    return (
      <li className="movie">{this.props.title}</li>
    );
  }