Ravi K
Ravi K

Reputation: 125

PropType optional to react component

I have the below common component

import PropTypes from 'prop-types';
import Input from '../component/Input'; //internal component 

const CustomInput = props => {
  const { label, updateInputField } = props;
  return (
    <Input
      label={label}
      changeField={updateInputField}
  )
}

CustomInput.propTypes = {
  label: PropTypes.string,
  updateInputField: PropTypes.func
}

export default CustomInput;

Now i am using these component at several places like below

<CustomInput 
  label="401Balance"
  updateInputField={inputFieldHandler}
/>

so this one works.. but there are some places where I am not using the updateInputField as a prop. for e.g.

<CustomInput 
  label="savingsBalance"
/>

How do i not pass the prop and ensure it doesnot fail. Can someone please suggest.

Upvotes: 0

Views: 1790

Answers (1)

kind user
kind user

Reputation: 41893

You could either set a default value to secure the case if no function was passed:

const { label, updateInputField = () => {} } = props;

or (probably a better approach) - create a separate function and add a simple condition:

const CustomInput = props => {
  const { label, updateInputField } = props;

  const fn = () => {
     if (updateInputField) {
        updateInputField();
     }
  };

  return (
     <Input
        label={label}
        changeField={fn}
     />
  );
}

Upvotes: 1

Related Questions