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
Functional components can accept and use props. Functional components should be favored if you do not need to make use of React state.
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.
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.
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> ); };
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> )
destructure logThis from props
const ChildComp = ({logThis}) => ( <button onClick={()=>logThis('test string')}>Click Here</button> ) export default ChildComp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With