Search code examples
reactjscomponents

Is it possible to add a component on button click where the button also exists within the same component in React ? If yes, how?


I'm new to React and tried googling this but could not find answers. Most cases, they had the ADD BUTTON in a different place, so it was easy for adding the child component on button click, but my scenario is a little bit different where the ADD BUTTON too is within the same CHILD COMPONENT which needs to get added upon ADD Button click.

Header Section of the Component
Text Box ----- Text Box ----- Text Box ----- Add Button ----- Remove Button

In the above example you can see, I have a component (lets say Component A) that is rendered within another component (Lets say Component B). I have the button for add which is also within the same Component A. So, when i Click Add Button it should add the same component and similarly for Remove option, it should remove the component on click of Remove Button. Is this possible ?

So, if i click Add 2 times, it would end up looking like below :

Header Section of the Component
Text Box ----- Text Box ----- Text Box ----- Add Button ----- Remove Button
Text Box ----- Text Box ----- Text Box ----- Add Button ----- Remove Button
Text Box ----- Text Box ----- Text Box ----- Add Button ----- Remove Button

Please forgive me if my question is lame. Something like this :

Something like this :


Solution

  • Step 1: Create state in parents component

    Parent.js
    const [data, setDate] = useState({}); 
    

    Step 2: Provide props {data, setData} for your child component

    Step 3: You have function which could change date and change the your dom.