Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
how to implement a delete button , which deletes every specific row by clicking it?

Its a program, which simply fetches a specific data, on every row by clicking "add record". I am having difficulty to execute delete button functionality , where on clicking it, that particular row will be deleted. Its should be implemented in DeleteHandler().

import React, { useState } from 'react'


const DataFetch = () => {

    const [posts, setPosts] = useState([]);

    const ClickHandler = () => {
        const url = `https://swapi.dev/api/people/${Math.floor(Math.random() * 10) + 1}`
        const fetchData = async () => {
            try {
                const response = await fetch(url);
                const json = await response.json();
                console.log(json);
                setPosts([...posts,
                   json.name])
            }
            catch (error) {
                console.log("error");
            }
        };
        fetchData();
    }

    const DeleteHandler = (e) => {
            const name = e.target.getAttribute("name")
            console.log(name)
    }

    return (
        <div>
            <div>
                <button onClick={ClickHandler}>ADD RECORD</button>
            </div>
            <table>
                {posts.map((post) =>
                    <tr>
                        <td key={Math.random()}>{post}</td>
                        <td><button name={post} onClick={()=>DeleteHandler}>delete</button></td>
                    </tr>
                )}
            </table>
        </div>
    );
};

export default DataFetch

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Within your DeleteHandler() function you should just be able to call setPosts() and set the posts to itself minus the row that was clicked, and then your JSX will know to re render itself and the row should no longer be there.

about 4 years ago · Juan Pablo Isaza Relatório

0

Use this code

import React, { useState } from "react";

let uidArray = [];

const DataFetch = () => {
  const [posts, setPosts] = useState([]);

  const ClickHandler = () => {
    const url = `https://swapi.dev/api/people/${
      Math.floor(Math.random() * 10) + 1
    }`;
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
        setPosts([...posts, json.name]);
      } catch (error) {
        console.log("error");
      }
    };
    fetchData();
  };

  const DeleteHandler = (e) => {
    const ele = document.getElementsByClassName(e)[0];
    ele.remove();
  };

  return (
    <div>
      <div>
        <button onClick={ClickHandler}>ADD RECORD</button>
      </div>
      <table>
        {posts.map((post) => (
          <tr className={post}>
            <td key={Math.random()}>{post}</td>
            <td>
              <button name={post} onClick={() => DeleteHandler(post)}>
                delete
              </button>
            </td>
          </tr>
        ))}
      </table>
    </div>
  );
};

export default DataFetch;

https://codesandbox.io/s/smoosh-breeze-rx7s0b

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda