简体   繁体   中英

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 eg

<CustomInput 
  label="savingsBalance"
/>

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

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}
     />
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM