What I have been trying is this:
The parent component is a class component with a function logToConsole. I summarized the code below:
I am trying to pass Function from parent component to a child functional component
Parent Component:
logToConsole = () => {
console.log("test);
}
render(){
return(
<ChildComp logThis={this.logToConsole} />
)
}
The ChildComp is:
const ChildComp = (props) => (
<button onClick={()=>props.logThis()}>Click Here</button>
)
export default ChildComp
However I am getting logThis is not a function. How do I solve this issue is there a better way to do this?
Parent:
import React from "react";
import Child from "./Child";
class Parent extends React.Component {
logToConsole = () => {
console.log("test");
};
render() {
return <Child log={this.logToConsole} />;
}
}
export default Parent;
Child:
export default function Child(props) {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={props.log}>Log</button>
</div>
);
}
Live Demo
Your child component should be:
<button onClick={props.logThis}>Click Here</button>
logToConsole = () => {
console.log("test);
}
should become
const logToConsole = () => {
console.log("test");
};