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

1.5k views Asked by At

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.

2

There are 2 answers

0
Mohammed Ashfaq On BEST ANSWER

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

0
Sylvie Art On

Fetching

  • Create api.
  • Create function fetching in sagas
  • Set index (sagas)
  • Create redux reducer to get data from fetching
  • In component mapping redux state to get data

Make list items

  • Try render function use return ListItem
  • It don't cluttered