DEV Community

Cover image for How to pass parameters from child commponent to parent component in React?
saurav RT
saurav RT

Posted on

2

How to pass parameters from child commponent to parent component in React?

Lets say we have a parent component App

import React from "react";
import { useState, useEffect } from "react";
import Search from "./Search";


const App = () => {
  const [SearchData, SetSearchData] = useState("Enter text");

  const ReceiveText = (txt) => {
    console.log(txt);
    SetSearchData(txt);
  };

  return (
    <div>
      <Search HandleSearch={ReceiveText} />
      <h1> {SearchData}</h1>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

and we have a child component Search


const Search = ({ HandleSearch }) => {
  return (
    <div classs="search">
      <label>Search </label>
      <input
        placeholder="Search for movies"
        onChange={(e) => HandleSearch(e.target.value)}

      />
      <br></br>
      <button>Search</button>
    </div>
  );
};

export default Search;

Enter fullscreen mode Exit fullscreen mode

App.js is a simple react component which has a child component Search.js. In app.js I have created a method which take an arguement text and print the text that we will be passing from child. also I have declared a usestate hook searchdata which would have initial text 'enter text' and also we will be setting the state based on the input from child.
In search.js file we are grabbing the method that is passed from App.js.Also it has a simple input tag from where we can input our text. it has an event handler onchange inside which iam calling handlesearch method which would get the text that we are entering from the input element and this text will be passed on to the handlesearch method of the parent component(App.js). As a result Searchdata would be updated which is in the App.js.
And that is how you can pass property from child to parent.
Thank you

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs