Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
Delete specific element in the array in localstorage using javascript and React

I have an array in localstorage and I am maping the array to render it's data into list. I want to add button next to every element in the list and if I click the button the specific element gets deleted from the array in the localstorage.

Is this possible and how can I do it?

Using -> Javascript and React code here:


//This array is in the localstorage
const reptiles = ["alligator", "snake", "lizard"];

function ReptileList() {

  return (
    <ol>
      {reptiles.map((reptile) => (
        <li>{reptile} /*THERE SHOULD BE THE DELETE BUTTON*/</li>
      ))}
    </ol>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Add some reptiles in the localStorage:

// in the Browser Console
localStorage.setItem( "reptiles", ["alligator", "snake", "lizard"] )

Or add some other functionalities to Add reptiles from the UI.

import "./styles.css";
import { useEffect, useState } from 'react';


export default function ReptileList() {

  const [ reptiles, setReptiles ] = useState( [] )

  function deleteReptile( name ){
    // Fin the index of the reptile
    let index = reptiles.indexOf( name )
    // if reptile is found
    if( index !== -1 ){
      // remove it from state
      reptiles.splice(index, 1 )
      // update localStorage
      localStorage.setItem( 'reptiles', reptiles )
      // update reptiles State to re-render the list
      setReptiles( [...reptiles] )
    }
  }

  function readReptiles(){
    // read from localStorage
    let reptiles = localStorage.getItem( 'reptiles' )
    
    // if no reptiles in localStorage initialize with empty
    if( reptiles === null ){
      reptiles =  []
    }
    // init reptiles State
    setReptiles( reptiles.split(',') )
  }

  useEffect(() => {
    // read reptiles from local storage after rendered
    readReptiles();
    return () => {};
  }, []);

  return (
    <div className="App">
      <h1>Reptiles</h1>
      {reptiles.map( (reptile => (
        <li key={reptile} >{reptile} - 
          <button onClick={()=>deleteReptile(reptile)}>Delete</button> 
        </li>
      )))}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use these 2 functions to Get and Remove Items from Local Storage.

const getElementsfromLocalStorage = () => {
    let elements = [];
    if (localStorage.getItem('reptiles')) {
        elements = JSON.parse(localStorage.getItem('reptiles'));
    }
    return elements;
};

const removeElementLocalStorage = (name) => {
    let elements = getElementsfromLocalStorage();
    elements = elements.filter(element => element.name !== name);
    localStorage.setItem('reptiles', JSON.stringify(elements));
};

Now, when you are rendering the list, render a button with every list item and call the function removeElementLocalStorage when the button is clicked with the value.

<li>
    <span>{reptile}</span>
    <button onClick={() =>removeElementLocalStorage(element.name)}>Remove</button>
</li>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda