Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a prop to a functional component

Tags:

I am trying to pass a function as a prop into a functional React component. I keep getting the error logThis is not a function.

The parent component is a class component with a function logToConsole. I summarized the code below:

logToConsole = (value) => {   console.log(value) } render(){   return(     <ChildComp logThis={this.logToConsole} />   ) }  

The ChildComp is:

const ChildComp = (logThis) => (   <button onClick={()=>logThis('test string')}>Click Here</button> )  export default ChildComp 
like image 231
PanczerTank Avatar asked Apr 26 '19 18:04

PanczerTank


People also ask

Can functional components have props?

Functional components can accept and use props. Functional components should be favored if you do not need to make use of React state.

How do you pass a function as props in React functional component TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

Can you pass in a component as a prop?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop.

How do you pass onClick as props in functional component?

Using functional components like in your example, you may use simply the following: const EditSubject = (props) => { return ( <div> <button onClick={() => begin(props)} // using props here > start </button> </div> ); };


2 Answers

The first parameter logThis will be props object itself.You need to destructure the logThis object.

const ChildComp = ({ logThis }) => (   <button onClick={() => logThis('test string')}>Click Here</button> ) 

Or you can access it from props

const ChildComp = (props) => (   <button onClick={() => props.logThis('test string')}>Click Here</button> ) 
like image 158
Maheer Ali Avatar answered Sep 20 '22 15:09

Maheer Ali


destructure logThis from props

const ChildComp = ({logThis}) => (   <button onClick={()=>logThis('test string')}>Click Here</button> )  export default ChildComp 
like image 42
Tahir Iqbal Avatar answered Sep 22 '22 15:09

Tahir Iqbal