Alanaj
Alanaj

Reputation: 247

How to develop previous and next buttons in React?

I am new to React and I am having a hard time trying to come up with code to make my buttons perform what I want. I want them to cycle through the array that they are given and display different information each time. I have tried for loop and forEach method and have tried adding the item to itself but nothing seems to work. I have tried to read the documentation on React but it gives me nothing. I don't know if there is a specific way to do it in React, can someone point me in the right direction?

Here is my code:

class Members extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: null,
      senators: [],
      represenatives: [],
      bills: [],
      
    }
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value.toUpperCase()
    })
  }

  right = (i) => {
    i.forEach(element => {
      element = element++
      console.log(element)
    });

  }
  left = (i) => {

    console.log(i.id)
  }

  componentDidMount() {
    const key = `xCaHBd8gI5ZJSOUXWFJGOXZBjJtMbvoIcip0kSmS`
    const urls = [`https://api.propublica.org/congress/v1/116/senate/members.json`,
      `https://api.propublica.org/congress/v1/102/house/members.json`,
      `https://api.propublica.org/congress/v1/statements/latest.json`,
      `https://api.propublica.org/congress/v1/bills/search.json`];

    let requests = urls.map(url => fetch(url, {
      type: "GET",
      dataType: 'json',
      headers: {
        'X-API-Key': key
      }
    }))
    Promise.all(requests)
      .then(res => {
        return Promise.all(res.map(res => res.json()));
      }).then(response => {
        this.setState({
          senators: response[0].results[0].members,
          represenatives: response[1].results[0].members,
          bills: response[2].results
        })
      }).catch(err => {
        console.log(err)
      })

  }

  render() {

    const { senators, bills, represenatives, userInput } = this.state;


    const inSenate = senators.filter(
      (senator) => senator.state === userInput
    )

    const inHouse = represenatives.filter(
      (represenative) => represenative.state === userInput
    )

    const draft = bills.find(
      (bill) => bill.name === inSenate.last_name)



    return (

      <div className="congress">
        <div className="users">
          <h2>{this.state.userInput}</h2>
          <input className="userInput" onChange={this.handleChange} />
        </div>

        {inSenate.map((senate, i) => {
          return (
            <div key={senate.id} className="senate">
              <h2 className="senateName">Senate</h2>
              <ul className="bio">
                <h2 >{senate.short_title + " " + senate.first_name + " " + senate.last_name}</h2>
                <li>{senate.title}</li>
                <li>State: <strong>{senate.state}</strong></li>
                <li>Party: <strong>{senate.party}</strong></li>
                <li>DOB: <strong>{senate.date_of_birth}</strong></li>
                <li>Next Election: <strong>{senate.next_election}</strong></li>
                <li>Missed Votes: <strong>{senate.missed_votes}</strong></li>
                <li> Votes With Party Percentage: <strong>{senate.votes_with_party_pct + "%"}</strong></li>
                <li>Votes Against Party Percentage: <strong>{senate.votes_against_party_pct + "%"}</strong></li>
              </ul>
            </div>
          )
        })}

        {inHouse.map((rep, i) => {
          return (
            <div key={rep.id} className="house">
              <h2 className="numbers" >Your state has {inHouse.length} Represenative(s)</h2>
              <h2 >{rep.short_title + " " + rep.first_name + " " + rep.last_name}</h2>
              <ul className="bio">
                <li  >{rep.title}</li>
                <li  >State: <strong>{rep.state}</strong></li>
                <li  >Party: <strong>{rep.party}</strong></li>
                <li  >DOB: <strong>{rep.date_of_birth}</strong></li>
                <li  >Next Election: <strong>{rep.next_election}</strong></li>
                <li  >Missed Votes: <strong>{rep.missed_votes}</strong></li>
                <li  > Votes With Party Percentage: <strong>{rep.votes_with_party_pct + "%"}</strong></li>
                <li  >Votes Against Party Percentage: <strong>{rep.votes_against_party_pct + "%"}</strong></li>
              </ul>
              <button onClick={() => this.left(inHouse)} className="left btn"></button>
              <button onClick={() => this.right(inHouse)} className="right btn"></button>
            </div>
          )
        })}
      </div>

    )
  }
}

Upvotes: 0

Views: 1071

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 695

Here is a solution. It uses states to change the information every time the button is pressed:

import React, { useEffect, useState, Component } from "react";
import { InputText } from "primereact/inputtext";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userInput: "CA",
      senators: [],
      represenatives: [],
      bills: [],
      repst: 0, //state for changing representative everytime the button is pressed
    };
  }

  handleChange = (e) => {
    this.setState({
      userInput: e.target.value.toUpperCase(),
    });
  };

  right = (i) => {
    if (this.state.repst + 1 < i.length)
      this.setState({
        repst: this.state.repst + 1,
      });
  };
  left = (i) => {
    if (this.state.repst - 1 > -1)
      this.setState({
        repst: this.state.repst - 1,
      });
  };

  componentDidMount() {
    const key = `xCaHBd8gI5ZJSOUXWFJGOXZBjJtMbvoIcip0kSmS`;
    const urls = [
      `https://api.propublica.org/congress/v1/116/senate/members.json`,
      `https://api.propublica.org/congress/v1/102/house/members.json`,
      `https://api.propublica.org/congress/v1/statements/latest.json`,
      `https://api.propublica.org/congress/v1/bills/search.json`,
    ];

    let requests = urls.map((url) =>
      fetch(url, {
        type: "GET",
        dataType: "json",
        headers: {
          "X-API-Key": key,
        },
      })
    );
    Promise.all(requests)
      .then((res) => {
        return Promise.all(res.map((res) => res.json()));
      })
      .then((response) => {
        this.setState({
          senators: response[0].results[0].members,
          represenatives: response[1].results[0].members,
          bills: response[2].results,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    const { senators, bills, represenatives, userInput } = this.state;

    const inSenate = senators.filter((senator) => senator.state === userInput);

    const inHouse = represenatives.filter(
      (represenative) => represenative.state === userInput
    );

    const draft = bills.find((bill) => bill.name === inSenate.last_name);

    return (
      <div className="congress">
        <div className="users">
          <h2>{this.state.userInput}</h2>
          <input className="userInput" onChange={this.handleChange} />
        </div>
        {inSenate.map((senate, i) => {
          return (
            <div key={senate.id} className="senate">
              <h2 className="senateName">Senate</h2>
              <ul className="bio">
                <h2>
                  {senate.short_title +
                    " " +
                    senate.first_name +
                    " " +
                    senate.last_name}
                </h2>
                <li>{senate.title}</li>
                <li>
                  State: <strong>{senate.state}</strong>
                </li>
                <li>
                  Party: <strong>{senate.party}</strong>
                </li>
                <li>
                  DOB: <strong>{senate.date_of_birth}</strong>
                </li>
                <li>
                  Next Election: <strong>{senate.next_election}</strong>
                </li>
                <li>
                  Missed Votes: <strong>{senate.missed_votes}</strong>
                </li>
                <li>
                  {" "}
                  Votes With Party Percentage:{" "}
                  <strong>{senate.votes_with_party_pct + "%"}</strong>
                </li>
                <li>
                  Votes Against Party Percentage:{" "}
                  <strong>{senate.votes_against_party_pct + "%"}</strong>
                </li>
              </ul>
            </div>
          );
        })}
        {inHouse[this.state.repst] ? (
          <div key={inHouse[this.state.repst].id} className="house">
            {console.log(inHouse)}
            <h2 className="numbers">
              Your state has {inHouse.length} Represenative(s)
            </h2>
            <h2>
              {inHouse[this.state.repst].short_title +
                " " +
                inHouse[this.state.repst].first_name +
                " " +
                inHouse[this.state.repst].last_name}
            </h2>
            <ul className="bio">
              <li>{inHouse[this.state.repst].title}</li>
              <li>
                State: <strong>{inHouse[this.state.repst].state}</strong>
              </li>
              <li>
                Party: <strong>{inHouse[this.state.repst].party}</strong>
              </li>
              <li>
                DOB: <strong>{inHouse[this.state.repst].date_of_birth}</strong>
              </li>
              <li>
                Next Election:{" "}
                <strong>{inHouse[this.state.repst].next_election}</strong>
              </li>
              <li>
                Missed Votes:{" "}
                <strong>{inHouse[this.state.repst].missed_votes}</strong>
              </li>
              <li>
                {" "}
                Votes With Party Percentage:{" "}
                <strong>
                  {inHouse[this.state.repst].votes_with_party_pct + "%"}
                </strong>
              </li>
              <li>
                Votes Against Party Percentage:{" "}
                <strong>
                  {inHouse[this.state.repst].votes_against_party_pct + "%"}
                </strong>
              </li>
            </ul>
            <button onClick={() => this.left(inHouse)} className="left btn">
              Next
            </button>
            <button onClick={() => this.right(inHouse)} className="right btn">
              Prev
            </button>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
}

Upvotes: 1

Related Questions