How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (2024)

Skip to content

How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (1)

Last Updated : 05 Sep, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

To pass the data from child to parent we will utilize the react’s unidirectional data flow. it means data is passed from parent components to child components. Here instead of passing data to child we will pass a function that sends the data back to the parent.

Approach

To pass data from the child to the parent component:

  • Define Callback: First, create a callback in the parent component. This callback function will retrieve the data from the child component.
  • Pass Callback as Prop: Pass the callback function to the child as a prop from the parent component.
  • Call the Callback: The child component calls the parent callback function using props and passes the data to the parent component.

Steps to Create React Application

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure: How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (3)

Example: This example defines a callback funtion as prop to pass data from child component to parent component.

JavaScript
// Filename - App.jsimport React from "react";import Child from "./Child";class App extends React.Component { state = { name: "", }; // Callback function to handle data received from the //child component handleCallback = (childData) => { // Update the name in the component's state this.setState({ name: childData }); }; render() { const { name } = this.state; return ( <div> <Child parentCallback={this.handleCallback} /> {name} </div> ); }}export default App;
JavaScript
// Filename - component/Child.jsimport React from "react";class Child extends React.Component { // Function triggered when the form is submitted onTrigger = (event) => { // Call the parent callback function this.props.parentCallback( event.target.myname.value ); event.preventDefault(); }; render() { return ( <div> <form onSubmit={this.onTrigger}> <input type="text" name="myname" placeholder="Enter Name" /> <br></br> <br></br> <input type="submit" value="Submit" /> <br></br> <br></br> </form> </div> ); }}export default Child;

Step to run the application: Open the terminal and type the following command.

npm start

Output:Open the browser and our project is shown in the URLhttp://localhost:3000/

How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (4)

In the above example we have used class components, It can also be done in react functional components with the help of useState hook.

Summary

React passes data from child to parent using callback functions defined in the parent, passed as props. The child calls the function, sending data up to the parent component.



Please Login to comment...

Similar Reads

How to pass property from a parent component props to a child component ?

Passing props from parent to child in React JS is an important concept. Props are read-only properties that are sent from the parent components to the child components. We can pass props in from parent to child using React JS functional as well as class components Table of ContentPassing Property Using Class ComponentsPassing Property Using Functio

3 min read

How to pass data from Parent to Child component in Angular ?

We can use the @Input directive for passing the data from the Parent to Child component in Angular Using Input Binding: @Input - We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is the child component. Parent Componentapp.component.

3 min read

How to force child div to be 100% of parent div's height without specifying parent's height?

When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem

3 min read

How to communicate from parent component to the child component in Angular 9 ?

Angular makes the communication between components very easy. In this article, we will learn how to communicate from a parent component to the child component. Approach: Let's create two components: parent child In the parent component, declare the property that you want to receive in the child component, say 'ParentId'. While including the child c

2 min read

How to Call Function Inside Child Component from Parent Component using useRef hook ?

In ReactJS, we can pass the function reference from parent components to child components. However, there are scenarios where you may need to call the function inside the child component from the parent component. It can be done by creating a reference using the useRef hook and createRef method as well. Prerequisites :NPM &amp; Node JSReact JSReact

2 min read

Passing data from Child to Parent Component in Angular

In Angular, passing data from a child component to its parent component involves emitting events. Essentially, the child component emits an event containing the data that the parent component needs to receive. This is typically achieved using Angular's EventEmitter class, where the child component emits an event with the data payload, and the paren

3 min read

How to Update Parent Data from Child Component in VueJS?

In Vue.js, communication between components is essential for building dynamic applications. One common scenario is updating the parent component's data from a child component. we will cover several ways to achieve this, including custom events, and v-model. Updating parent data from a child component allows the parent to react to changes in the chi

3 min read

How to Pass Data from One Component to Another Component in ReactJS ?

In React, passing data from one component to another component is a common task. It helps build a dynamic and interactive web application. We can pass data in components from parent to child, child to parent, and between siblings as shown below. We have 3 approaches to share or pass the data between React components. Table of Content Passing data f

5 min read

How to remove parent element except its child element using jQuery ?

Given an HTML document and the task is to remove the parent element except for its child element. Approach 1: Use contents() method to select all the direct children, including text and comment nodes for the selected element.Selected elements are stored in a variable.Now, use replaceWith() method to replace the content of parent element by its all

2 min read

How to expand floated child div's height to its parent's height in CSS ?

Making the height of the floating child div equal to the height of the parent div is referred to as expanding the height of the floated child div to the height of the parent div. Approach 1: Using the CSS "clearfix" method is the first approach to increase a floated child div's height to match its parent's height. When an element is floated, it is

4 min read

How to Call Parent Components's Function from Child Component in React ?

In React, it is very important to manage communication between components for building flexible and maintainable applications. Sometime, you need to trigger a function defined in a parent component from a child component. In this article, we'll see how to achieve this in React by passing down functions as props from parent to child components. Tabl

3 min read

How to Call a Parent Method from a Child Component in Vue 3 ?

Vue.js is a JavaScript framework for building user interfaces. In Vue 3 parent and child component can communicate with each other through props and events. Props are used to pass the data from the parent to the child component and events are used to pass the data from child to parent component. These are the following approaches: Table of Content

3 min read

Write a program to pass values to child using context in ReactJS ?

Passing values to chile in react js is an important concept in react js. It simply can be achieved by using prop drilling but it is not the right way in case of big project. Hence we will pass the values to child using context in react js with the help of useContext Hook. PrerequisitesReact JSReact JS useContext HookApproachTo pass values to child

4 min read

How to Pass Value from One Child Component to Another in VueJS ?

Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. In this article, we will learn how to pass value from one child component to another in VueJS. There are sometimes when we need

3 min read

How To Share Data Between Child And Parent Directives And Components In Angular?

Sharing data between child and parent components in Angular is important for building dynamic and interactive applications. This can be done through various concepts, including input and output bindings or using a shared service. This article will explore how to use an Angular service to enable data communication, allowing both parent and child com

5 min read

How to set Parent State from Children Component in ReactJS?

We can set Parent State from Children Component in ReactJs using the following approach. Prerequisite: State introduction in ReactJS We will actually set the state of a parent in the parent component itself, but the children will be responsible for setting.We will create a function in parent to set the state with the given input.We will pass that f

3 min read

Explain lifecycle of component re-rendering due to re-rendering of parent component

React is a javascript library that renders components written in JSX. You can build and render any component as per your usage. States can be updated accordingly using the setState method. Props can be updated only by the parent component. Updating of state and props leads to the rendering of UI. Different lifecycle methods are called during these

2 min read

jQuery parent &gt; child Selector

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Syntax: ("parent &gt; child")Parameter Values: parent: Using this, the parent element will be selected.child: Using this, the direct child element of the specified parent element will be selected.Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html

1 min read

How to navigate to a parent route from a child route?

In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g

4 min read

How to return true if the parent element contains the child element in JavaScript ?

In JavaScript, children property returns an array of those elements which are children of a given element. In order to check whether the parent element (say x) contains a child element (say y), we can use the children property to get the array of all children of x and then check whether the array obtained contains y. To get the child element of a p

2 min read

How to apply CSS in last child of parent using jQuery ?

In this article, we will see how to set styles in the last child of the parent element using jQuery. To set the style on the last child of parent, we use jQuery :last-child selector. The :last-child selector is used to select every element that is the last child of its parent element. Syntax: $("Selector:last-child") Approach: First, we create an H

1 min read

How to Style Parent Element when Hover Over a Child Element in CSS ?

In this article, we will learn how to style the parent element when hovering over a child element. Styling the parent element when hovering over a child element is a useful CSS technique that allows you to change the appearance of the parent element when the mouse cursor is hovering over one of its child elements. This can be useful for adding inte

2 min read

How to Make a Child Div Element Wider than Parent Div using CSS ?

When the child div element has a fixed width that is wider than the parent div element, it will display overflow outside of the parent element. Because the overflow is hidden by default, one approach is to utilize the overflow attribute to enable it on an element. Another approach includes setting the position property of the parent div element to

2 min read

How to make Parent Div Activate Styling of Child Div for Hover and Active ?

In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active. Approaches to make parent div activate styling of child div for hover and activeUsing Pure CSS: with pseudo-classesUsing CSS and JavaScript: without pseudo-classesMethod 1: Using Pure

2 min read

How to Check if an element is a child of a parent using JavaScript?

In this article, we are going to see the methods by which we can Check if an element is a child of a parent using JavaScript. These are the following methods: Table of Content Using the Node.contains() methodLooping through the parents of the given childUsing the hasChildNodes() methodMethod 1: Using the Node.contains() methodThe Node.contains() me

4 min read

How to Access Child Method From the Parent in VueJS ?

In this article, we are going to discuss how can we access the child method from the parent in VueJS. We need to create such a component that shows the use of accessing the child methods from the parent component. Approach:We will create two components ParentMethod and ChildComponent.ParentMethod vue.js component consists of a parent component whic

3 min read

How does useImperativeHandle help parent and child components communicate?

useImperativeHandle in React allows parent and child components to communicate more effectively by enabling the child component to specify which methods and properties should be accessible to the parent through a ref. How Does It Help:Customized Interaction: Child components can define a specific set of functions or data they want to share with the

2 min read

Parent to Child Communication with Metadata in Angular 17

A parent component in Angular can transfer data or information to its child components using parent-to-child communication. This is an essential component of creating reusable and modular Angular applications. This is an overview of Angular 17's parent-to-child communication features. PrerequisitesBasic JavaScriptBasic AngularWhat is Parent to Chil

2 min read

How to apply style to parent if it has child with CSS?

While we are familiar with applying styles to child elements when a parent class is present, sometimes we need to apply styles to a parent element based on its child elements. Although CSS does not natively support parent selectors, there are ways to achieve similar effects using combinators and JavaScript. Understanding Child CombinatorsA child co

2 min read

How to call a parent method from child class in JavaScript?

Inheritance in programming allows a class to derive methods and properties from another class, similar to how a child inherits traits from its parents. A child class can have its properties in addition to inherited ones. The deriving class is called a derived, sub, or child class, while the class it derives from is the base, super, or parent class.

3 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (6)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

How to Pass Data from Child Component to its Parent in ReactJS ? - GeeksforGeeks (2024)
Top Articles
Blog Post Examples and Best Practices to Inspire Your Writing
FSG-Alliance-Wealth-version-1.6
3 Tick Granite Osrs
Time in Baltimore, Maryland, United States now
855-392-7812
Pangphip Application
Myexperience Login Northwell
Academic Integrity
Athletic Squad With Poles Crossword
Ogeechee Tech Blackboard
Ave Bradley, Global SVP of design and creative director at Kimpton Hotels & Restaurants | Hospitality Interiors
Whitley County Ky Mugshots Busted
5808 W 110Th St Overland Park Ks 66211 Directions
Oc Craiglsit
Nioh 2: Divine Gear [Hands-on Experience]
Nissan Rogue Tire Size
Mzinchaleft
Tygodnik Polityka - Polityka.pl
2024 INFINITI Q50 Specs, Trims, Dimensions & Prices
Aes Salt Lake City Showdown
Vernon Dursley To Harry Potter Nyt Crossword
Обзор Joxi: Что это такое? Отзывы, аналоги, сайт и инструкции | APS
Soul Eater Resonance Wavelength Tier List
HP PARTSURFER - spare part search portal
Valley Craigslist
The Creator Showtimes Near Baxter Avenue Theatres
Ehome America Coupon Code
Craigslist Texas Killeen
Craigslist Maryland Baltimore
Forager How-to Get Archaeology Items - Dino Egg, Anchor, Fossil, Frozen Relic, Frozen Squid, Kapala, Lava Eel, and More!
Nacho Libre Baptized Gif
AsROck Q1900B ITX und Ramverträglichkeit
Louisville Volleyball Team Leaks
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
3400 Grams In Pounds
968 woorden beginnen met kruis
Davis Fire Friday live updates: Community meeting set for 7 p.m. with Lombardo
Clima De 10 Días Para 60120
Man Stuff Idaho
Ezpawn Online Payment
Pekin Soccer Tournament
Subdomain Finder
Shipping Container Storage Containers 40'HCs - general for sale - by dealer - craigslist
3 bis 4 Saison-Schlafsack - hier online kaufen bei Outwell
Www Craigslist Com Atlanta Ga
2017 Ford F550 Rear Axle Nut Torque Spec
The Sports Academy - 101 Glenwest Drive, Glen Carbon, Illinois 62034 - Guide
8 4 Study Guide And Intervention Trigonometry
Windy Bee Favor
Lesson 5 Homework 4.5 Answer Key
Black Adam Showtimes Near Cinemark Texarkana 14
Island Vibes Cafe Exeter Nh
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 6640

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.