pass props to parent component in react.js

  • Last Update :
  • Techknowledgy :

Is there not a simple way to pass a child's props to its parent using events, in React.js? Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props. Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React The question is how to pass argument from child to parent component. This example is easy to use and tested:

This is our Splunktool team suggestion ✌, we tried and its working fine
/* Parent */
    // The Parent creates the function to be used by the Child and
    // whenever the Child calls the function, it is triggered from
    // the Parent.const Parent = () => {
  const saveProjectFunction = data => {
    // Recieving data(object) from the Child, instead of passing
    // the object to the Child.
    const modData = {
        id: 1,
        ...data
    }
    console.log(`From the Parent ${modData}`);
  }
  return(
        <Child onSaveProject={saveProjectFunction}/>
    )
}
​
// NOTE: YOU CAN'T SKIP INTERMEDIATE COMPONENT
// The way you pass down through each component, is the same way
// You pass up without skipping a component/* Child */
  // The child basically calls the function from the parent which was
  // pass in as props, but the function lives and is being used in
  // the parent.const Child = ({ onSaveProject }) => {
  const sendData = () => {
    const data = {
        name: "kouqhar",
        sport: "basketball"
    }
    // Sending the created data(object) to the Parent instead of
    // Recieving data from the Parent.
    onSaveProject(data)
  }
    return(
        <button onClick={sendData}><button/>
      )
}
​
// With love @kouqhar

Child: it really does not have to be more complicated than that.

var Child = React.createClass({
  render: function () {
    return <button onClick={this.props.onClick}>{this.props.text}</button>;
  },
});

Parent with single child: using the value it passes to the child

var Parent = React.createClass({
  getInitialState: function() {
     return {childText: "Click me! (parent prop)"};
  },
  render: function () {
    return (
      <Child onClick={this.handleChildClick} text={this.state.childText}/>
    );
  },
  handleChildClick: function(event) {
     // You can access the prop you pass to the children 
     // because you already have it! 
     // Here you have it in state but it could also be
     //  in props, coming from another parent.
     alert("The Child button text is: " + this.state.childText);
     // You can also access the target of the click here 
     // if you want to do some magic stuff
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

This is for me a bad idea in term of coupling and encapsulation:

var Parent = React.createClass({
  handleClick: function(childComponent) {
     // using childComponent.props
     // using childComponent.refs.button
     // or anything else using childComponent
  },
  render: function() {
    <Child onClick={this.handleClick} />
  }
});

Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:

<Child ref="theChild" ... />

Suggestion : 2

Most developers wonder about passing props from a child to a parent component when learning React. However, it’s not possible. Let's update the previous example with an additional Button component for toggling. In this guide, we’ve covered various ways to pass props in a React app. Remember that props are read-only and enable us to pass any data down our component tree. However, what makes React really interactive is the state system. Note that the above can cause performance issues because every time our component renders, a new object gets created each time. However, for someone starting to learn React, that should be fine.

1._
1import React, { Component } from 'react';
2class App extends Component {
3  render() {
4    const hello = 'Say Hello to learning Props/State in React!';
5    return (
6      <div>
7        <h1>{hello}</h1>
8      </div>
9    );
10  }
11}
12export default App;
2._
1import React, { Component } from 'react';
2class App extends Component {
3  render() {
4    return (
5      <div>
6        <HelloReact />
7      </div>
8    );
9  }
10}
11
12class HelloReact extends Component {
13  render() {
14    const hello = 'Say Hello to learning Props/State in React!';
15    return <h1>{hello}</h1>;
16  }
17}
18export default App;
3._
1import React, { Component } from 'react';
2class App extends Component {
3  render() {
4    const hello = 'Say Hello to learning Props/State in React!';
5    return (
6      <div>
7        <HelloReact hello={hello} />
8      </div>
9    );
10  }
11}
12class HelloReact extends Component {
13  render() {
14    return <h1>{this.props.hello}</h1>;
15  }
16}
17export default App;
5._
1const HelloReact = ({ hello }) => <h1>{hello}</h1>;
6._
1import React, { Component } from 'react';
2class App extends Component {
3  render() {
4    return (
5      <div>
6        <HelloReact hello="Say Hello to learning Props/State in React!" />
7      </div>
8    );
9  }
10}
11const HelloReact = ({ hello }) => <h1>{hello}</h1>;
12export default App;

Suggestion : 3

React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, and functions. This Gallery component contains some very similar markup for two profiles. Extract a Profile component out of it to reduce the duplication. You’ll need to choose what props to pass to it. The Clock component below receives two props from its parent component: color and time. (The parent component’s code is omitted because it uses state, which we won’t dive into just yet.)

1._
function Avatar() {
  return (
    <img
      className="avatar"
      src="https://i.imgur.com/1bX5QH6.jpg"
      alt="Lin Lanying"
      width={100}
      height={100}
    />
  );
}

export default function Profile() {
  return (
    <Avatar />
  );
}

2._
export default function Profile() {  return (    <Avatar />  );}
3._
export default function Profile() {  return (    <Avatar      person={{ name: 'Lin Lanying', imageId: '1bX5QH6' }}      size={100}    />  );}
5._
import { getImageUrl } from './utils.js';

function Avatar({ person, size }) {
  return (
    <img
      className="avatar"
      src={getImageUrl(person)}
      alt={person.name}
      width={size}
      height={size}
    />
  );
}

export default function Profile() {
  return (
    <div>
      <Avatar
        size={100}
        person={{ 
          name: 'Katsuko Saruhashi', 
          imageId: 'YfeOqp2'
        }}
      />
      <Avatar
        size={80}
        person={{
          name: 'Aklilu Lemma', 
          imageId: 'OKS67lh'
        }}
      />
      <Avatar
        size={50}
        person={{ 
          name: 'Lin Lanying',
          imageId: '1bX5QH6'
        }}
      />
    </div>
  );
}

6._
function Avatar(props) {
   let person = props.person;
   let size = props.size; // ...}

Suggestion : 4

The child component calls the parent function to send data to the parent. The child component receives the reference to the parent function as a prop. Then it does a function call with parameters that we want to pass to the parent. Reactjs allows one-way data binding, meaning passing data down the hierarchy from parent to child. To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive. Here we pass the callback function reference to the child component as a prop. It is important to pass the reference to the function. Not the function callback() which will result in immediate execution of the function.

1._
import { useState } from "react"
import { Child } from "./Child"
export const Parent = () => {
    const [name, setName] = useState<string|undefined>()
    const callback = (name: string | undefined) => {
        setName(name)
    }
    return(
        <>
            <div>{name}</div>
            <div><Child onClick={callback}/></div>
        </>
    )
}
2._
import { useRef } from "react"
export interface ChildProps{
    onClick: (name: string|undefined) => void
}
export const Child = (props: ChildProps) => {
    const inputName = useRef<HTMLInputElement>(null)
    const onButtonPress = () => {
        props.onClick(inputName?.current?.value)
    }
    return(
        <>
            <input ref={inputName} type="text"/>
            <button onClick={onButtonPress}>Callback</button>
        </>
    )
}

Suggestion : 5

React.js allows us to use props (short form of property) to pass data from parent component to child component. We have to set props value inside the child component, while we embed it to the parent component. Pass the props to the child component as an argument while embedding it to the parent component. Filename: App.js In this file, we will embed the child component to the parent component. Also, we pass multiple props to the child component. When users pass the data from parent to child using the class components, they can access inside the child component using ‘this.props.property_name‘. 

Creating Application: The below command will help you to start a new react app.

npx create - react - app testapp

Next, you have to move to the ‘testapp‘ project folder from the terminal.

cd testapp

Example: 

import React, { Component } from 'react';
import Child from './components/child.js';
 
// Child component embedded to parent component
// with props value
class App extends Component {
  render() {
    return (
      <div>
        <h1>This is a parent component</h1>
        <ul>
         <li>
          <Child gfgcolor="green" usercolor="blue"/>
         </li>
        </ul>
      </div>
    );
  }
}
  
export default App;

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

npm start

Example: 

Filename: App.js In App.js, we will add a functional component and call a child component with props and their value. 

import React, { Component } from 'react';
import Child from './components/child.js';
 
// parent component
// embedding child component inside it
function App (){
  return(
    <div>
    <h1>This is a parent component</h1>
    <ul><li>
  <Child gfgcolor="green" usercolor="blue"/></li>
  </ul>
  </div>
  )
}

Suggestion : 6

In child component we called that function using props.Changedata("child") and set a value inside the function parameter that value gonna effect to the state of parent's state and its turn into this value. . State is similar to props, but it is private and fully controlled by the component.You can make dynamic data using state. source ** In this parent component we have set initiate state value to "parent" and pass a function to the child component using props.

1._
import { useState } from "react";
import Child from "./child";
const App = () => {
  const [Name, setName] = useState("Parent");

  return (
    <>
      <h1>{Name}</h1>
      <Child Changedata={(Name) => setName(Name)} />
    </>
  );
};

export default App;


2._
const Child = (props) => {
  return (

   <button 
   onClick={() => props.Changedata("Child")}>
   Change</button>

  )
};

export default Child;




Suggestion : 7

Since props can only be passed from parent to child components, how can a child component communicate with its parent component? This a common question for React beginners once they learned about props in React and the answer for it is brief: there is no way to pass props from a child to a parent component. For example, props can be passed not only from a parent to a child component, but also from ancestor components to descendant components: Basically that's how props are passed from component to component in React. As you may have noticed, props are only passed from top to bottom in React application's component hierarchy. There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial.

Normally you start out with React's JSX syntax for rendering something to the browser when learning about React. Basically JSX mixes HTML with JavaScript to get the best of both worlds:

import * as React from 'react';
const App = () => {  const greeting = 'Welcome to React';
  return (    <div>      <h1>{greeting}</h1>    </div>  );}
export default App;

A bit later you will split out your first React :

import * as React from 'react';
const App = () => {  return (    <div>      <Welcome />    </div>  );};
const Welcome = () => {  const greeting = 'Welcome to React';
  return <h1>{greeting}</h1>;};
export default App;

A common question followed by this refactoring: how to pass the data from one React component to another component? After all, the new component should render a dynamic greeting, not the static greeting that is defined within the new component. It should behave like a function which I can pass parameters after all.

Entering React props -- where you can pass data from one component to another in React -- by defining custom HTML attributes to which you assign your data with JSX's syntax:

import * as React from 'react';
const App = () => {  const greeting = 'Welcome to React';
  return (    <div>      <Welcome text={greeting} />    </div>  );};
const Welcome = (props) => {  return <h1>{props.text}</h1>;};
export default App;

As you have seen, props enable you to pass values from one component to another component down the component tree. In the previous example, it was only a string variable. But props can be any JavaScript data type from integers over objects to arrays. Via props you can even pass React components as well, which you will learn about later.

For what it's worth, you can also define the props inline without declaring a variable before:

import * as React from 'react';
const App = () => {  return (    <div>      <Welcome text={"Welcome to React"} />    </div>  );};
const Welcome = ({ text }) => {  return <h1>{text}</h1>;};
export default App;

In the case of a JavaScript string, you can pass it as props inside double quotes (or single quotes) too:

import * as React from 'react';
const App = () => {  return (    <div>      <Welcome text="Welcome to React" />    </div>  );};
const Welcome = ({ text }) => {  return <h1>{text}</h1>;};
export default App;