Basic overview of how callback functions work in React.js:

Basic overview of how callback functions work in React.js:

  • Defining a Callback Function:First, you need to define a callback function. This function can be a regular JavaScript function or an arrow function, depending on your preference and requirements.javascriptCopy code

function myCallback() {
  // Code to be executed when the callback is called
}
        

  • Passing the Callback as a Prop:You typically pass the callback function as a prop to a child component. This allows the child component to execute the callback when a certain event occurs.javascriptCopy code

// ParentComponent.js

import React from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  // Define the callback function
  function myCallback() {
    console.log('Callback function called');
  }

  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent callback={myCallback} />
    </div>
  );
}

export default ParentComponent;
        

  • Using the Callback in the Child Component:In the child component, you can access the callback function via the props and call it when needed. For example, you might call the callback in response to a button click:javascriptCopy code

// ChildComponent.js

import React from 'react';

function ChildComponent(props) {
  function handleClick() {
    // Call the callback function when the button is clicked
    props.callback();
  }

  return (
    <div>
      <h2>Child Component</h2>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

export default ChildComponent;
        

  • Callback Execution:When the "Click me" button in the child component is clicked, it will trigger the handleClick function, which in turn calls the myCallback function passed as a prop from the parent component. This allows you to execute code in the parent component in response to an event in the child component.

This is a basic example of using callback functions in React.js. Callbacks are also commonly used with asynchronous operations like fetching data from an API, where you pass a callback function to handle the data once it's available.

Remember that in modern React, you can also use hooks like useState and useEffect to manage state and side effects, which can sometimes replace the need for callback functions in certain scenarios.

要查看或添加评论,请登录

Hasitha Madusanka的更多文章

社区洞察

其他会员也浏览了