Home > OS >  removing an item from an array in ReactJS
removing an item from an array in ReactJS

Time:04-15

I am learning React and I can't seem to figure out how to remove an item from an array. I have tried couple of ways but it either removes the entire array or more than one item in the array so I can't find any working solution. Here is my code:

App.js:

import React, { useState } from 'react';
import Education from './Education';

export default function App() {
  const [educationArray, setEducationArray] = useState([]);
  const handleDeleteEduItem =(id)=>{
  
    const eduArrayToSplice = [...educationArray]
    const newEduArray = eduArrayToSplice.splice(id, 1)
    
    setEducationArray(newEduArray)
    console.log(id)
  }
  return (
    <div className="App">
    <div className="edit-mode">
    <h4>Education</h4>
    <button onClick={()=>{setEducationArray([...educationArray, <Education id={educationArray.length} handleDeleteButton={handleDeleteEduItem}/>])}}>add new</button>
    {educationArray.map((eduItem, i)=><div className="eduItem" key={i}>{eduItem}</div>)}
       
     
    </div>
    </div>
      
  );
}

And the functional component:

import React, { useState} from 'react';

function Education(props)

 {
       const [schoolName, setSchoolName] = useState('');
       const [major, setMajor] = useState('');
       const [studyFrom, setStudyFrom] = useState('')
       const [studyTo, setStudyTo] = useState('');
       const [degree, setDegree] = useState('');
       const [displayEducationSection, setEducationSection] = useState(false)
      
    

       const changeSchoolName = (e) => {
              setSchoolName(e.target.value);
            };
          
       const changeMajor = (e) => {
              setMajor(e.target.value);
            };
       const changeStudyFrom =(e)=> {
              setStudyFrom(e.target.value);
            };
       const changeStudyTo =(e)=> {
              setStudyTo(e.target.value)
            };
       const changeDegree =(e) => {
              setDegree(e.target.value);
            };
       const flipEducationSection =()=> {
              setEducationSection(!displayEducationSection)
            };
   

          
          
    return(
        <div className="education-section">
            {displayEducationSection ? 
            <div>
              <p>School Name: {schoolName}</p>
              <p>Major: {major}</p>
              <p>from: {studyFrom}</p>
              <p>to: {studyTo}</p> 
              <p>Degree: {degree}</p> 

            </div>
            :
            <form onSubmit={(e)=>e.preventDefault()} className="education-form">
            <label>
                   School Name:<input value={schoolName} onChange={changeSchoolName} />
            </label>
            <label>
                   Major:<input value={major} onChange={changeMajor} />
            </label>
            <label>
                   From:<input value={studyFrom} onChange={changeStudyFrom} />
            </label>
            <label>
                   To:<input value={studyTo} onChange={changeStudyTo} />
            </label>
            <label>
                   Degree:<input value={degree} onChange={changeDegree} />
            </label>

                
            </form>}
            <button onClick={flipEducationSection}>{displayEducationSection ? 'edit' : 'save'}</button>
            <button onClick={()=>props.handleDeleteButton(props.id)}>delete</button>
        </div>
    )

}



export default Education;

I've also used the following function to try to remove an item from the array, but it doesn't remove the clicked item but removes all items that come after it:

const handleDeleteEduItem =(id)=>{
  const newEduArray = educationArray.filter((item)=>educationArray[item] !== id)
  
  setEducationArray(newEduArray)
  console.log(educationArray)
}

CodePudding user response:

I think you don't want to filter directly the state. What you could do instead is:

setEducationArray((cv) => cv.filter((e) => e.id !== id ))

This way you get to access the current value in your educationArray state (cv), and filter that to get all elements where the e.id is not equal to the id you have given to your id.

Edit:

To be fair, I'm not sure how your array eventually looks like. But if it was an array of objects, with each object having its own id. Then I would suggest the thing I wrote above.

CodePudding user response:

you can not directly update the state with using same memory location. you have to create new memory to updated array and then update the component state. you will see quickly changes on UI.

else this function will help you to remove single item from array. you have to

ensure that your id should be unique for each item.

const handleDeleteEduItem =(id)=>{

const eduArrayToSplice = [...educationArray.filter(item)=>item.id!==id)]   
setEducationArray(newEduArray)
console.log(id)

}

  • Related