Reputation: 1130
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
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
Reputation: 323
destructure logThis from props
const ChildComp = ({logThis}) => (
<button onClick={()=>logThis('test string')}>Click Here</button>
)
export default ChildComp
Upvotes: 3
Reputation: 661
Change to:
const ChildComp = (props) => (
<button onClick={()=>props.logThis('test string')}>Click Here</button>
)
export default ChildComp
Upvotes: 2