Home > database >  how can I remove part of data from state in react.js
how can I remove part of data from state in react.js

Time:02-28

I create and add some data to my selecetFile2 state / then I want to delete some part of that selecetFile2 state by any event- just guide for function.

const [selectedFile2, setSelectedFile2] = useState([]); //my state for data
const [isFilePicked2, setIsFilePicked2] = useState(false); //just controll for page

this function for control data

    const changeHandler2 = (event) => {
       setSelectedFile2([...selectedFile2,event.target.files[0]]);
       setIsFilePicked(true);}

    const multi_img = ()=>{ //It's for input dialog box
        document.getElementById("multi_img").click();}

this my main code

     <input type="file" onChange={changeHandler2} title="ali ali"  id="multi_img" 
        name="img" accept="image/*"  style={{display:'none'}} />
        <div><BsFillPlusSquareFill onClick={multi_img} /> //input control by this
        {
            isFilePicked2 &&
                selectedFile2.map(item => <img key={v4()} src={URL.createObjectURL(item)} />)
          //this my Item I want to delete for example by click
          //I just need function
        }

CodePudding user response:

Here you go

 <input
      type="file"
      onChange={changeHandler2}
      title="ali ali"
      id="multi_img"
      name="img"
      accept="image/*"
      style={{ display: "none" }}
    />
    <div>
      <BsFillPlusSquareFill onClick={multi_img} /> //input control by this
      {
        isFilePicked2 &&
          selectedFile2.map((item) => (
            <img key={v4()} src={URL.createObjectURL(item)} onClick={ () => {
              setSelectedFile2(selectedFile2.filter(i => i !== item))
            }} />
          ))
        //this my Item I want to delete for example by click
        //I just need function
      }
    </div>

CodePudding user response:

By using useState, you can not directly update or modify the state. Whenever you wanted to modify or update the state you have to do it using the set[nameofstate]. In your case. whenever you want to update selectedFile2 you have to pass the new value for seletedFile2 to setSelectedFile2(newValueForSelectedFile2). for more information and examples please visit documenation

  • Related