1

So, Ii'm using React right now to build out a simple app per an assignment. Now, I know you can render a bunch of gifs based on a search result from user input, but how do I only render specific results I choose?

For example, if I just wanted to present a page of reaction gifs, or a page of funny cat gifs, without user input.

Furthermore, what if I then wanted to paginate those results by maybe 10 gifs a page?

I've been unable to find a clear answer online so any help you guys could render would be greatly appreciated. Thank you in advance.

rxistheone
  • 11
  • 2

1 Answers1

3

You want to set a query that's not controlled by the user, fetch those results and render them. Pagination is fairly straightforward, use the limit and offset parameters of the API (Docs).

Very basic example:

class Category extends React.Component {
  constructor() {
    super();
    this.state = { data: [], paginate: 0 };
    this.fetchNextPage = this.fetchNextPage.bind(this);
  }

  componentDidMount() {
    this.fetchData();
  }

  fetchData() {
    fetch(`https://api.giphy.com/v1/gifs/search?q=${this.props.query}&limit=${this.props.limit}&offset=${this.state.paginate}&api_key=dc6zaTOxFJmzC`)
      .then(res => res.json())
      .then(data => this.setState({ data: data.data }));
  }

  fetchNextPage() {
    this.setState({
      paginate: this.state.paginate + this.props.limit
    }, () => this.fetchData());
  }

  render() {
    return (
      <div>
        <button onClick={this.fetchNextPage}>Next Page</button><br />
        {this.state.data.map(gif => (
            <img
              key={gif.id}
              src={gif.images.fixed_width_small.url}
            />
          ))}
      </div>
    );
  }
}

ReactDOM.render(
  <Category query="cats" limit={10} />,
  document.getElementById("View")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>
Fabian Schultz
  • 18,138
  • 5
  • 49
  • 56
  • Hey, that's very helpful thank you, but here's a further question I've been struggling with, what if I needed it in a tab view? Say for example, I wanted a React page that displayed a tabbed view, allowing a user to switched between paginated results of Kittens and Puppies. How exactly would I do that? – rxistheone Feb 17 '17 at 20:16
  • Stack Overflow is not a tutorial website. There is a lot of [information](https://github.com/reactjs/react-tabs) [on](https://www.npmjs.com/package/react-simpletabs) [this](https://www.npmjs.com/package/react-tabs-navigation) [online](https://toddmotto.com/creating-a-tabs-component-with-react/). – Fabian Schultz Feb 17 '17 at 23:13