react-nativereact-native-flatlistreact-native-button

React Native: What is the best way to make a list of button elements given data from a Fetch(Url) request?


I want to make a list of button elements that the user can tap. The amount of button elements will vary from 3 - 5 depending on the result of a fetch request that I do. I know how to populate a flatlist based on the result of a fetch request but not the contents of a button. Any help?

For example, using this JSON, suppose I wanted to render buttons for the amount of movies in there, each button having the name of the movie. The amount of movies will vary.


Solution

  • If you set the movies to a state after Api response like this.

    this.setState({movies: apiResponse.movies})
    

      
    
    renderMovieList(){
        return  this.state.movies.map((movie, i, movieArray) =>
          <View 
            key={movie.id} 
            style={{ height:50, padding:20}}>
            <Button
              onPress={()=> this.handleOnPress(movie)}
              title={movie.title}
              color="#841584"
              accessibilityLabel="Learn more about this purple button"
            />
          </View>
        )
      }
      
      handleOnPress(movieDetails){
       alert(movieDetails.title);
      }
    
      render() {
        return (
          <View style={{flex: 1, justifyContent:'center', backgroundColor: "#0d98ba"}}>
            {this.state.movies.length? this.renderMovieList(): null}
          </View>
        );
      }

    See full code here