viorel Grigoras
viorel Grigoras

Reputation: 19

How do I send a function through props in react typescript

Hei! I'm trying to have a button component to make 2 separate things : One is called "START" and I want to start a countdown from my StoreTimer.start() ... And the other one is "RESET" where I want to reset my countdown from my StoreTimer.reset(). The problem is that I don't know how to do it . Let's take for example my code:

<StartButton name="Start"
              onClick={()=>{StoreTimer.start()}}/>
              <StartButton name="Reset"
              onClick={()=>{StoreTimer.reset()}}/>
            </div>
          </div>

here is my Home component where I imported StartButton , I want that button to have 2 different option to be reusable .... for example to start my countdown and reset it ... depends on the function that I pass...

here is my component

export interface Props {
  name?: string;
  color?: string;
  onClick?: () => void;
}

export const StartButton: React.FC<Props> = ({ name, color,onClick }) => {
  return (
    <>
      <div className="Buttons">
        <button
          className={"myButton"}
          style={{ backgroundColor: color }}
          onClick={() => onClick}
        >
          {name}
        </button>
      </div>
    </>
  );
};
export default StartButton;

If I make a separated component for start and reset and I don't pass the function through props it work... but I want to reuse the component StartButton and do 2 different thighs : Reset and Start . How I can do that? Please help me understand.

Upvotes: 0

Views: 97

Answers (1)

Zouhair Dre
Zouhair Dre

Reputation: 628

Try adding () to your props function,and change the name onClick it is confusing :)

<button className={"myButton"}
        style={{ backgroundColor: color }}
        onClick={() => onClick()}
        >
        {name}
</button>

or like this :

<button className={"myButton"}
        style={{ backgroundColor: color }}
        onClick={onClick}
        >
        {name}
</button>

Upvotes: 2

Related Questions