How to pass a Function as a Prop in React | bobbyhadz (2024)

# Table of Contents

  1. How to pass a Function as props in React
  2. Pass a function with arguments as a Prop
  3. Pass a function as a Prop from the Child to the parent
  4. Adding extra functionality to the function in the Child component
  5. Pass onChange event handler to Child component in React

# How to pass a Function as props in React

To pass a function as props in React:

  1. Define the function in the parent component.
  2. Pass it as a prop to the child component.
  3. Use the function in the child component.

App.js

Copied!

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 ( <div> <h2>Count is: {count}</h2> <Child handleClick={handleClick} /> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (1)

The code for this article is available on GitHub

We passed a function as a prop to a child component in React.

App.js

Copied!

<Child handleClick={handleClick} />

Notice that we didn't call the function when passing it as a prop. It's very important to pass a reference to the function and not the result of calling the function.

If you pass the result of calling the function, e.g.handleClick={handleClick()}, then it would get invoked immediately when thepage loads, which is not what we want.

If you need to pass a function as props in React TypeScript, check outthe following tutorial.

# Pass a function with arguments as a Prop

If you want to pass a parameter to the function that you are passing as a prop,use an inline arrow function.

App.js

Copied!

import {useState} from 'react';function Child({handleClick}) { return <button onClick={handleClick}>Increment</button>;}export default function App() { const [count, setCount] = useState(0); function handleClick(event, num) { console.log('Function ran in Child component'); setCount(count + num); } return ( <div> <h2>Count is: {count}</h2> <Child handleClick={event => handleClick(event, 100)} /> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (2)

The code for this article is available on GitHub

We passed a parameter to the handleClick function when passing it as a prop tothe Child component. However, note that we are still passing a function as aprop, and not the result of calling one.

The event parameter might not be needed for your use case. All event handlers get called with the event object as the first argument, so we had to pass it to the function in this example.

# Pass a function as a Prop from the Child to the parent

If you need to pass a function as a prop from the Child to the Parent component:

  1. Define a function in the Parent component that takes a parameter.
  2. Call the function from the Child, passing it another function as a parameter.
  3. Call the function in the Parent component.

App.js

Copied!

import {useState} from 'react';function Child({handleClick}) { const logger = () => { console.log('Function defined in Child'); }; return ( <div> <button onClick={event => handleClick(logger)}>Click</button> </div> );}export default function Parent() { const [count, setCount] = useState(0); const handleClick = func => { // 👇️ call the function the Child component passed func(); setCount(count => count + 1); }; return ( <div> <Child handleClick={handleClick} /> <h2>Count: {count}</h2> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (3)

The code for this article is available on GitHub

The handleClick function in the Parent component takes another function as aparameter.

We passed the function as a prop to the Child component and called it, passingit the logger() function.

Everything handleClick is invoked, we call the function from the Childcomponent and update the state.

I've also written a detailed guide onhow to call a child function from a parent component.

# Adding extra functionality to the function in the Child component

You can also add extra functionality to the function you passed as a prop to thechild component.

App.js

Copied!

import {useState} from 'react';function Child({handleClick}) { // 👇️ wrap passed in function function wrapHandleClick(event) { // 👉️ your logic before console.log('Child called handleClick'); handleClick(event); // 👉️ your logic after } return <button onClick={wrapHandleClick}>Increment</button>;}export default function App() { const [count, setCount] = useState(0); function handleClick(event, num) { setCount(count + num); } return ( <div> <h2>Count is: {count}</h2> <Child handleClick={event => handleClick(event, 100)} /> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (4)

The code for this article is available on GitHub

We wrapped the handleClick function into another function where we can run some extra logic before or after calling it.

This is useful when you have to await the return value of a Promise or run somelogic based on the return value of the passed function.

# Pass onChange event handler to Child component in React

To pass an onChange event handler to a child component:

  1. Define the event handler function in the parent component.
  2. Pass it as a prop to the child component.
  3. Set it to the onChange prop on the input field in the child.

App.js

Copied!

import {useState} from 'react';function Child({handleChange}) { return ( <input id="message" name="message" onChange={handleChange} /> );}export default function App() { const [message, setMessage] = useState(''); function handleChange(event) { setMessage(event.target.value); } return ( <div> <Child handleChange={handleChange} /> <h2>Message is: {message}</h2> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (5)

The code for this article is available on GitHub

We passed a handleChange function to a child component.

Notice that we didn't call the function when passing it as a prop. It's very important to pass a reference to the function, not the result of calling the function.

If you pass the result of calling the function, e.g.handleChange={handleChange()}, then it would get invoked immediately on pageload, which is not what we want.

# Pass onChange event handler with parameter to Child component

If you want to pass a parameter to the function that you are passing as a prop,use an inline arrow function.

App.js

Copied!

import {useState} from 'react';function Child({handleChange}) { return ( <input id="message" name="message" onChange={handleChange} /> );}export default function App() { const [message, setMessage] = useState(''); function handleChange(event, anotherParam) { console.log(anotherParam); setMessage(event.target.value); } return ( <div> <Child handleChange={event => handleChange(event, 'another param')} /> <h2>Message is: {message}</h2> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (6)

The code for this article is available on GitHub

We passed a parameter to the handleChange function when passing it as a propto the Child component. However, note that we are still passing a function asa prop, and not the result of calling one.

# Adding extra functionality to the handleChange function

You can also add extra functionality to the function you passed as a prop in thechild component.

App.js

Copied!

import {useState} from 'react';function Child({handleChange}) { function wrapHandleChange(event) { console.log('Child triggered onChange'); // 👉️ your logic before handleChange(event); // 👉️ your logic after } return ( <input id="message" name="message" onChange={wrapHandleChange} autoComplete="off" /> );}export default function App() { const [message, setMessage] = useState(''); function handleChange(event) { setMessage(event.target.value); } return ( <div> <Child handleChange={handleChange} /> <h2>Message is: {message}</h2> </div> );}

How to pass a Function as a Prop in React | bobbyhadz (7)

The code for this article is available on GitHub

We wrapped the handleChange function into another function where we can runsome extra logic before calling it or after.

This is useful when you have to await the return value of a Promise or run somelogic based on the value of the input field.

How to pass a Function as a Prop in React | bobbyhadz (2024)

FAQs

Can you pass a function as a prop in React? ›

You can think of props as custom attributes for components in React. To pass a function, you can simply reference the name of the variable that stores the function. In this case, that would be handleClick variable. In this case, the name of the prop (the custom attribute) is handler .

How do you pass elements as props in React? ›

Props, short for properties, are the mechanism by which React components communicate with each other. They are read-only and allow the passing of data from parent components to child components. Props can include simple data like strings and numbers, but they can also include functions and even other components.

How to pass a function as a prop from child to parent in React? ›

Quick and easy:
  1. Create a function inside your parent component, pass it a parameter and log that parameter using console. log .
  2. Pass the function name as props into your child component render.
  3. Invoke the function from props inside your child component.
  4. Pass in your data as an argument inside the invocation.
  5. Viola.

How to pass function in context React? ›

To pass context:
  1. Create and export it with export const MyContext = createContext(defaultValue) .
  2. Pass it to the useContext(MyContext) Hook to read it in any child component, no matter how deep.
  3. Wrap children into <MyContext.Provider value={...}> to provide it from a parent.

What is props function in React? ›

Props stand for properties. They are read-only values that can be passed across components in order to display relevant data in your React apps. Take an example of a simple JavaScript function. In it, we pass two parameters, a and b, to manipulate them inside the function and return the sum of both parameters.

How to pass state as props in React? ›

To pass a state variable to another component that is not related, you will need to lift the state up to a common ancestor component and then pass it down as a prop to the desired component.

How do you pass a key prop in React? ›

For extracting components, assign the key prop to that <Component /> and not the <li> inside that component. Keys must only be unique among siblings and not globally. React does not pass the key as a prop automatically to a component. Assigning random key attributes will reduce the performance.

How to call function from child to parent in React? ›

The easiest way is to use the useImperativeHandle hook. It allows you to expose certain functions to the parent component. To use it, we need to wrap our component in a forwardRef call and pass the ref to the useImperativeHandle hook.

How to pass function as props in React functional component? ›

state , depending on which syntax and build steps you are using.
  1. Bind in Constructor (ES2015) class Foo extends Component { constructor(props) { super(props); this. ...
  2. Class Properties (ES2022) class Foo extends Component { handleClick = () => { console. ...
  3. Bind in Render. ...
  4. Arrow Function in Render.

How do you pass a function? ›

Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action. This turns out to be extremely useful.

How to pass value from child to parent in React? ›

Approach:
  1. In the parent component, create a callback function. ...
  2. Pass the callback function to the child as a prop from the parent component.
  3. The child component calls the parent callback function using props and passes the data to the parent component.
Nov 23, 2023

Can we pass props to functional component? ›

In order to to make props accessible in a function component you need to pass the props argument to the function and then you can access props by using the props object inside the function.

Can I pass a function as a prop in Vue? ›

In Vue you can pass strings, arrays, numbers, and objects as props. But can you pass a function as a prop? While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem.

How to pass a function as a prop in NextJS? ›

Next. js utilizes a file-based routing system, which means each page is a separate component file. To pass props between pages in Next. js, you can use the getStaticProps() or getServerSideProps() functions.

Can you pass a ref as a prop React? ›

There is one caveat to the above example: refs will not get passed through. That's because ref is not a prop. Like key , it's handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.

Top Articles
6 Tips For How to Build a Soundproof Room Within a Room
7 Ways Governments Fight Deflation
Rest Area Cerca De Mí
World War II: Summary, Combatants & Facts | HISTORY
Davis.k12.Ut.us
Qvc Uk Marla Wynne
Ucf Net Price Calculator
The TBM 930 Is Another Daher Masterpiece
Cheap Manicure Near Me
Benefit Solutions.ehr.com Tenet
Caroline G. Atkinson Intermediate School
Personapay/Glens Falls Hospital
Pokemon Infinite Fusion How To Get All Starters
Stetson Exam Schedule
Lesson 2 Homework 2.5
Craigslist Sac Boats
Horses For Sale In Nm Craigslist
Kwabena Agyei-Agyemang on LinkedIn: #youtube #work #gaming
Muddy Paws Livermore
Veronica Correia titt*es
Jasper William Oliver Cable Alexander
Craigslist Apartments For Rent Imperial Valley
Vacbanned Steam Hex
Math-Aids.com Answers
Austin Eaccess
Hummul Carving Company
Craiglist Quad Cities
Christmas Days Away
The Philadelphia Inquirer from Philadelphia, Pennsylvania
The Year The Internet Stopped Laughing
0Gomovies To To
O-Ring Sortiment online kaufen | WÜRTH
Matthew Rotuno Johnson
Gabrielle Abbate Obituary
Buy affordable car tyres
This Modern World Daily Kos
Centricity Kp Schedule
Lenscrafters Westchester Mall
The Complete Buying Guide to Casio G-Shock Watches: The Vast Collection, Explained | Gear Patrol
Bed linen made in Portugal from linen
ZTO International tracking - Track123
How To Get The Unphased Badge In Slap Battles
Meriwest Login
Adam Bartley Net Worth
Viewfinder Mangabuddy
Target hiring On - Demand Guest Advocate in Port Chester, NY | LinkedIn
Full Cast Of Red
Gdp E239 Bts
Ter Review
Radical Red Ability Pill
Days Calculator 📅 (Days Between Dates)
Used cars for sale in Lagos
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6366

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.