PanczerTank
PanczerTank

Reputation: 1130

Passing a function as a prop to a functional component

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

Upvotes: 38

Views: 59344

Answers (3)

Maheer Ali
Maheer Ali

Reputation: 36564

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>
)

Upvotes: 44

Tahir Iqbal
Tahir Iqbal

Reputation: 323

destructure logThis from props

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

export default ChildComp

Upvotes: 3

user2343647
user2343647

Reputation: 661

Change to:

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

export default ChildComp

Upvotes: 2

Related Questions