J
J
JekaHC2022-04-05 23:16:23
JavaScript
JekaHC, 2022-04-05 23:16:23

How to add a "show more" button to every card in React?

I have a React component:

Main.jsx

import { useState, useEffect } from "react";

import { Preloader } from "../Preloader";
import { Pokemons } from "../Pokemons";
import { LoadMore } from "../LoadMore";

function Main() {
  const [pokemons, setPokemons] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pokemonsPerPage] = useState(20);
  const [page, setPage] = useState(1);

  function getPokemons(pokemonOffset) {
    fetch(
      `https://pokeapi.co/api/v2/pokemon?limit=${pokemonsPerPage}&offset=${pokemonOffset}`
    )
      .then((responce) => responce.json())
      .then((data) => {
        data.results && setPokemons((p) => [...p, ...data.results]);
        setLoading(false);
      });
  }

  useEffect(() => {
    const offset = page * pokemonsPerPage - pokemonsPerPage;

    getPokemons(offset);
  }, [page]);

  return (
    <main className="container content">
      {loading ? <Preloader /> : <Pokemons pokemons={pokemons} />}
      <LoadMore next={() => setPage((p) => p + 1)} />
    </main>
  );
}

export { Main };


Pokemon.jsx

import React from "react";
import { useState, useEffect } from "react";
import { TailSpin } from "react-loader-spinner";

function Pokemon({ name, url }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((r) => r.json())
      .then(setData);
  }, [url]);

  return (
    <div>
      {data ? (
        <div className="card animate__animated animate__bounceInUp">
          <div className="card-image">
            <img src={data.sprites.front_default} />
            <span className="card-title">{name}</span>
            {/* {???.map((item, index) => (
              <div key={index}>
                <button onClick={()=> {??? }}>Sakra</button>
              </div>
            ))} */}
          </div>
          <div className="card-content">
            {data.abilities.map((n, index) => (
              <p key={index}>{n.ability.name}</p>
            ))}
          </div>
        </div>
      ) : (
        <div>
          <TailSpin type="Puff" color="purple" height={100} width={100} />
        </div>
      )}
    </div>
  );
}

export { Pokemon };


I need each card (Pokémon) to have a "Details" button that when clicked displays additional (unique) information from the fetch request in the "url" for the selected card.

I think I need to do this in Pokemon.jsx because in Main.jsx the existing fetch request doesn't fit.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2022-04-06
@SilenceOfWinter

You here https://freelance.habr.com

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question