In my parent component(App.js) i am passing a function as a prop to the child:
import React from "react";
import Win from "./components/Win"
function App() {
const [squares, setSquares] = React.useState(dices)
const [allSame, setAllSame] = React.useState(false)
function Reset() {
console.log("yes")
}
return (
<Win onClick = {() => Reset} />
}
export default App;
this is my child component(Win.js):
import React from "react"
import reset from "../images/reset.png"
import Confetti from "./Confetti"
export default function Win(props) {
// function r(){
// console.log("lol")
// }
return (
<div className="Win">
{/* <Confetti /> */}
<h1 style={{color:"white", fontSize:"4rem"}}>You Won</h1>
<button onClick={() => props.Reset}>Press ME</button>
</div>
)
}
i made the function r just for testing and tried using it when the button is clicked, it worked perfectly fine.
2
Answers
You’re not calling the function inside the arrow function. Use
()
to invoke it. Also, the name of the prop passed to the child isonClick
, notReset
.Alternatively, directly pass the function reference itself to
onClick
.Reset
is a simple function, let’s write it as() => console.log("yes")
.In the
onClick
property ofWin
you wrap it in a function, so we have<Win onClick={() => () => console.log("yes")} />
.In the
onClick
property ofbutton
you wrap it in a function once again, so now we have<button onClick={() => () => () => console.log("yes")} />
.So while you want to pass a function that prints to console, you pass a function that returns a function that returns a function that prints to console.
Since you start with a function that prints to console, you should simply pass it without wrapping in new functions.
Also, from
App
you pass the property with the nameonClick
while inWin
you try to read it asReset
. Change it to one of them.