kiran karedla
kiran karedla

Reputation: 169

How to pass down event from parent to child in react with functional components?

I have two buttons in my Parent component AddRow and DeleteRow buttons if i click on addRow button it will add an empty row in grid and if i click deleteRow button it will delete selected rows from grid. I have added two functions for adding row to grid and removing record from grid in my child component. How to call these functions from parent component button click events. Similar sample code given below.

i have used lift up state to parent component it is working is any other way to do it because i need to move entire child component code to parent component and there are 4 child components lifting the all the child code to parent becomes huge code in parent component what is the react way doing things in this situation.

import { render } from 'react-dom';
import React, { useState } from 'react';
    
const App = () => {
  return (
    <Parent />
  );
};
    
const Parent = () => { 
  return (
    <div>
      <h1>Parent Component</h1>
      <div id="newElements"></div>
      <input type="button" value="Add New Element" onClick={} />
      <input type="button" value="Clear Elements" onClick={} />  
      <Child />
    </div>
  )
};
    
const Child = () =>{  
  function addElement() {
    // this function will add row to grid.
    var node = document.createElement("h1");  

    node.innerHTML="New Element";
    document.getElementById('newElements').appendChild(node); 
  }

  function clearElement() {
    // this function will remove row from grid
    document.getElementById('newElements').innerHTML=""; 
  }

  return (
    <div>
      <h1>Child Component</h1>
        // here the grid will be there in my actual code 
        <div id="newElements"></div>
      </div>
  )
};

render(<App />, document.getElementById('root'));

I need to call addElement() function when click on parent components AddNewElement button.

Upvotes: 8

Views: 24309

Answers (0)

Related Questions