2

I created a react component which takes 2 props: func1, func2.

const Component = ({ func1, func2 }) => {
  return (
          <Button
            onClick={() => {
              func1();
              func2();
            }}
            
          >
            Click
          </Button>
  );
};

The above component is reusable. I have a situation where I pass both functions (func1, func2) as props in this component:

<Component func1={functionA} func2={functionC}/>

I also have situations where I don't pass both props:

<Component func1={functionA}/>

In the last case, how to set the func2 as alternative prop?

6
  • what do you mean by "alternative" prop? Commented Jul 16, 2020 at 12:18
  • How about calling funct1 and funct2 on conditional basis? funct1 && funct1() Commented Jul 16, 2020 at 12:19
  • @Apostolos, i mean, when i will use <Component/> like in the last case i don't want to get the error, that i forgot to pass func2. I need to change something in the Component, and to be prepared that both props could be use not as required. Commented Jul 16, 2020 at 12:21
  • 1
    @AskMen, so I guess Neeko's answer fits your needs. I would make a small change though. instead of null i would say func2 = () => return false Commented Jul 16, 2020 at 12:23
  • 1
    @AskMen check my answer to the other question Commented Jul 16, 2020 at 12:31

2 Answers 2

1

You can simply set a default parameter when you declare your component:

const Component = ({ func1, func2 = null }) => {
  return (
          <Button
            onClick={() => {
              func1();
              if (func2 && typeof func2 === "function") {
                func2();
              }
            }}
            
          >
            Click
          </Button>
  );
};

Your func2 will now be equal to null (or whatever value you want to assign) when no prop is provided.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is an example to how to do it:

const ParentFunc2 = () => {
  console.log("ParentFun2");
};

export default function App() {
  return (
    <div className="App">
      <TestComponent func2={ParentFunc2} />
    </div>
  );
}

TestComponent:

import React from "react";

const func1Default = () => {
  console.log("func1");
};

const func2Default = () => {
  console.log("func2");
};

export default function TestComponent({
  func1 = func1Default,
  func2 = func2Default
}) {
  return (
    <button
      onClick={() => {
        func1();
        func2();
      }}
    >
      Click{" "}
    </button>
  );
}

Live example:

https://codesandbox.io/s/falling-rgb-xidfe?file=/src/App.js

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.