skip to Main Content

In React I am showing a grid. In that I have kept a delete icon with a delete method. This is column layout for that grid:

export const ObjectEx = [
{
    name: "Test1",
    field: "Test1"
    edit: true,
    action: (cellProps) => {
       return (<div><Icon name="Delete" onClick={this.delete} /></div>)
    }

}
]

Here the delete action need to call in this component. The component code is as follows:

export default class ObjectCategory extends Component {
    //here in this class I need call delete
    constructor(props) {
      super(props)
    }

    delete() {
       // delete action code
    }

    return (
       <div>Here my code will added</div>
    )
}

How can call that delete action method from that class to this class in React?

I tried calling this calling that delete in the component code but it is not working.

2

Answers


  1. There are 2 ways to do it.

    You can pass the function as prop to your child component.

    const functionName = () => {} 
    <ChildComponent propName={functionName}
    

    Then in child conponent

    const ChildComponent = ({propName}) => {
    
    
         // propName will be passed as a function to your component and now you can use it where ever u want.
    }
    

    If above method involves lot of components to pass the function, then use CONTEXTAPI and pass the use it with CONTEXT consumer.

    Login or Signup to reply.
  2. Pass that function using props to the component and use that function in that component accordingly.
    import {useState} from ‘react’;

    function Child({handleClick}) {
      return <button onClick={handleClick}>Increment</button>;
    }
    
    export default function App() {
      const [count, setCount] = useState(0);
    
    function handleClick() {
        console.log('Function ran in Child component');
        setCount(count + 1);
    }
    

    return (

    Call Child component like this

      <Child handleClick={handleClick} />
    

    );
    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search