Reputation: 14165
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:
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:
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>
);
}
Upvotes: 2
Views: 83
Reputation: 15632
render()
of MovieList
:
render() {
return (
<div className="movies">
{
this.state.movies
? <ul>
{this.state.movies.map((movie, index) => <Movie title={movie.title} key={index}/>)}
</ul>
: null
}
</div>
);
}
render()
of Movie
:
render() {
return (
<li className="movie">{this.props.title}</li>
);
}
Upvotes: 1
Reputation: 2308
i props/state - I think what you're doing is fine; passing your outer component's (MoviesList) state down to its child as a prop (you wouldn't set the outer component's own properties with the result of the api call).
ii You can map over the movies in your outer component, for example:
renderMovie(movie) {
return (
<Movie movie={movie} />
);
}
render()
{
return (
<div className="movies">
<ul>
{ this.state.movies.map(this.renderMovie) }
</ul>
</div>
);
}
Upvotes: 1