skip to Main Content

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


  1. You’re not calling the function inside the arrow function. Use () to invoke it. Also, the name of the prop passed to the child is onClick, not Reset.

    <button onClick={() => props.onClick()}>
    <Win onClick = {() => Reset()} />
    

    Alternatively, directly pass the function reference itself to onClick.

    <button onClick={props.onClick}>
    <Win onClick={Reset} />
    
    Login or Signup to reply.
  2. Reset is a simple function, let’s write it as () => console.log("yes").

    In the onClick property of Win you wrap it in a function, so we have <Win onClick={() => () => console.log("yes")} />.

    In the onClick property of button 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.

    <Win onClick={Reset} />
    <button onClick={props.onClick}>
    

    Also, from App you pass the property with the name onClick while in Win you try to read it as Reset. Change it to one of them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search