Search code examples
javascriptreactjsreact-hooksjsxreact-functional-component

Add and Remove the Component onClick function


I started on React project. using functional components and hooks for development.

function comp1{
const addHandeler = () =>{
 //how to add component
}
return(<div> 
 <comp2/>
 // on click of add <comp2/> ...
<input type="button" id="add" value="Add" 
                            onClick={addHandeler} />
</div>)
}

I want to add multiple component comp2 on click of Add button inside div.

function comp2{

const deleteHandeler = () =>{
 // how to delete the component from comp1
}

return(
<div>
...
<input type="button" id="delete" value="Delete" 
     onClick={deleteHandeler}  />
</div>
)
}

similarly will have delete button, which will remove the comp2 from comp1 div. Or let me know if there are any other best way to accomplish this.


Solution

  • since you are adding and removing a list of components you need to have a unique identifier once create each one. here is a simplified vesion on how to approach with nanoId (you use it to create the id from new elements, not call it on map):

    Comp1

    import { nanoid } from 'nanoid'
    
    function Comp1() {
      const [ids, setIds] = useState([])
      const addHandeler = () => {
        const newId = nanoid()
        setIds(ids => [...ids, newId])
      }
    
      const deleteHandeler = (removeId) => setIds(ids => ids.filter(id => id !== removeId))
      return(
        <div>
          { ids.map(id => <Comp2 key={id} deleteHandeler={() => deleteHandeler(id)} />) }
    
          <input type="button" id="add" value="Add" onClick={addHandeler} />
        </div>
      )
    }
    

    Comp2

    function Comp2({ deleteHandeler }) {
      return (
      <div>
      <input type="button" id="delete" value="Delete" 
            onClick={deleteHandeler} />
      </div>
      )
    }
    

    my-description